void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                var progressIndicator = SystemTray.ProgressIndicator;
                if (progressIndicator != null)
                {
                    return;
                }

                progressIndicator = new ProgressIndicator();

                SystemTray.SetProgressIndicator(this, progressIndicator);

                Binding binding = new Binding("IsLoading") { Source = _viewModel };
                BindingOperations.SetBinding(
                    progressIndicator, ProgressIndicator.IsVisibleProperty, binding);

                binding = new Binding("IsLoading") { Source = _viewModel };
                BindingOperations.SetBinding(
                    progressIndicator, ProgressIndicator.IsIndeterminateProperty, binding);

                progressIndicator.Text = "Loading games...";
                _viewModel.LoadPage(lastPagePulled, PAGE_COUNT);
                lastPagePulled += 1;
            }
            catch (Exception exception)
            {
                ErrorHandler.Save(exception, MobileTypeEnum.WP8);
            }
        }
 // Common Progress Indicator show and hide functions
 // `that` is required for SystemTray to know what to attach the progress indicator to.
 public static void showProgressIndicator(string message, DependencyObject that, ProgressIndicator progressIndicator)
 {
     progressIndicator.IsIndeterminate = true;
     progressIndicator.IsVisible = true;
     progressIndicator.Text = message;
     SystemTray.SetProgressIndicator(that, progressIndicator);
 }
        private async void GetPrivateMessages()
        {
            try
            {
                var progress = new ProgressIndicator
                {
                    IsVisible = true,
                    IsIndeterminate = true,
                    Text = "Downloading private messages..."
                };

                SystemTray.SetProgressIndicator(this, progress);

                List<PrivateMessageRepository> messages = await ApiController.GetUserPrivateMessages();

                progress.IsVisible = false;

                App.ViewModel.LoadData(privateMessages: messages);
            }
            catch (Exception e)
            {
                var error = e.Message;
            }
            
        }
        private void OnLoaded(object sender, EventArgs eventArgs)
        {
            var progressIndicator = SystemTray.ProgressIndicator;
            if (progressIndicator != null)
            {
                return;
            }

            progressIndicator = new ProgressIndicator();

            SystemTray.SetProgressIndicator(this, progressIndicator);

            Binding binding = new Binding("IsLoading") { Source = _viewModel };
            BindingOperations.SetBinding(
                progressIndicator, ProgressIndicator.IsVisibleProperty, binding);

            binding = new Binding("IsLoading") { Source = _viewModel };
            BindingOperations.SetBinding(
                progressIndicator, ProgressIndicator.IsIndeterminateProperty, binding);

            progressIndicator.Text = "Loading new tweets...";
            _viewModel.LoadPage(SearchTerm, _pageNumber++);

            var parentPage = App.RootFrame.Content as PhoneApplicationPage;
            if (parentPage != null)
            {
                parentPage.ApplicationBar = Resources["appbarTwitter"] as ApplicationBar;
                parentPage.ApplicationBar.IsVisible = true;
            }
        }
Example #5
0
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                indicator = new ProgressIndicator
                {
                    IsVisible = true,
                    IsIndeterminate = true
                };
                SystemTray.SetProgressIndicator(this, indicator);
                CameraButtons.ShutterKeyPressed += CameraButtons_ShutterKeyPressed;
                LoadShooter(CameraType.FrontFacing);

                var wc = new WebClient();
                wc.DownloadStringCompleted += DownloadStringCompleted;
                var searchUri = string.Format(
                  "http://gdata.youtube.com/feeds/api/videos?q={0}&format=6",
                  HttpUtility.UrlEncode("harlem shake"));
                wc.DownloadStringAsync(new Uri(searchUri));
                shake = ShakeGesturesHelper.Instance;
                shake.ShakeGesture += shake_ShakeGesture;
                RootLayout.SelectionChanged += RootLayout_SelectionChanged;
            }
            catch (Exception ex)
            {
            }
        }
        public Login()
        {
            InitializeComponent();
            try
            {

                progressIndicator = SystemTray.ProgressIndicator;
                progressIndicator = new ProgressIndicator();

                SystemTray.SetProgressIndicator(this, progressIndicator);
                progressIndicator.IsIndeterminate = true;
                progressIndicator.Text = "Logging In...";

                SqlFactory fact = new SqlFactory();
                var user = fact.GetProfile();
                if (user != null)
                {
                    EmailAddress.Text = user.UserName;
                }
            }
            catch (Exception exception)
            {
                ErrorHandler.Save(exception, MobileTypeEnum.WP8);
            }
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            try
            {
                Voting = new VotingClass();
                //(App.Current as App).SecondPageObject = null;
                progressIndicator = SystemTray.ProgressIndicator;
                progressIndicator = new ProgressIndicator();
                SystemTray.SetProgressIndicator(this, progressIndicator);
                progressIndicator.IsIndeterminate = true;
                progressIndicator.Text = "Pulling Poll...";
                if (SettingsMobile.Instance.User == null)
                {
                    SqlFactory fact = new SqlFactory();
                    SettingsMobile.Instance.User = fact.GetProfile();
                }
                Voting.VotingId = Convert.ToInt64(this.NavigationContext.QueryString["pid"]);
                PullTopic();


            }
            catch (Exception exception)
            {
                ErrorHandler.Save(exception, MobileTypeEnum.WP8);
            }

        }
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);

            //Load Europeana API
            EuropeanaAPI = new EUPwebclient();
            EuropeanaAPI.searchDoneEvent += new EUPwebclient.searchDone(EuropeanaAPI_searchDoneEvent);

            //Load GPS
            phoneGPS = new GPS();
            phoneGPS.posFoundEvent += new GPS.posFound(phoneGPS_posFoundEvent);

            //Load city finder
            cityFinder = new googleCityLookup();
            cityFinder.cityFoundEvent += new googleCityLookup.cityFound(cityFinder_cityFoundEvent);

            //Progress bar control
            SystemTray.SetIsVisible(this, true);
            SystemTray.SetOpacity(this, 0);
            prog = new ProgressIndicator();
            prog.IsVisible = true;
            prog.IsIndeterminate = true;
            prog.Text = "Loading...";
            SystemTray.SetProgressIndicator(this, prog);

            this.BackKeyPress += new EventHandler<System.ComponentModel.CancelEventArgs>(MainPage_BackKeyPress);
        }
Example #9
0
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (this.NavigationContext.QueryString.ContainsKey("path"))
            {
                this.folderPath = NavigationContext.QueryString["path"];
            }
            if (this.NavigationContext.QueryString.ContainsKey("id"))
            {
                this.fileID = NavigationContext.QueryString["id"];
            }
            if (this.NavigationContext.QueryString.ContainsKey("filename"))
            {
                this.filename = this.NavigationContext.QueryString["filename"];
                this.filenameInput.Text = this.filename;
            }

            if (this.fileID != null)
            { // try to get file contents

                this.progressIndicator = new ProgressIndicator();
                this.progressIndicator.IsIndeterminate = true;
                this.progressIndicator.IsVisible = true;
                this.progressIndicator.Text = "Looking for rain...";
                SystemTray.SetProgressIndicator(this, this.progressIndicator);

                LiveConnectClient client = new LiveConnectClient(App.Current.LiveSession);
                client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnFileDownloadComplete);
                client.DownloadAsync(this.fileID+"/content");
            }
            else
            {
                this.contentInput.IsEnabled = true;
                this.filenameInput.Focus(); // doesn't work as it is here, maybe because page isn't actually loaded yet?
            }
        }
        // Constructor
        public MainPage ()
            {
            InitializeComponent ();
            Utilities.MainPageControl = this;
            Unloaded += Page_Unloaded;
            InitializeAppBarButtons ();
            _saveMenuItem = ApplicationBar.MenuItems[0] as ApplicationBarMenuItem;
            _saveMenuItem.IsEnabled = false;

            if (!IsolatedStorageSettings.ApplicationSettings.Contains (Constants.TOTAL_SECONDS))
                IsolatedStorageSettings.ApplicationSettings.Add (Constants.TOTAL_SECONDS, "60");

            if (!IsolatedStorageSettings.ApplicationSettings.Contains (Constants.MINUTE_SECOND_KEY))
                IsolatedStorageSettings.ApplicationSettings.Add (Constants.MINUTE_SECOND_KEY, Constants.MINUTE);

            IsolatedStorageSettings.ApplicationSettings.Save ();

            UpdateButtonState (false, false, true, false, false);

            _progressIndicatror = new ProgressIndicator
            {
                IsVisible = false,
                IsIndeterminate = true,
                Text = "Stopping..."
            };
            SystemTray.SetProgressIndicator (this, _progressIndicatror);

            }
Example #11
0
        private void TopGamePage_Loaded(object sender, RoutedEventArgs e)
        {
            this.TopStreamsList.ItemsSource = _viewModel.StreamList;
            var progressIndicator = SystemTray.ProgressIndicator;
            if (progressIndicator != null)
            {
                return;
            }

            progressIndicator = new ProgressIndicator();

            SystemTray.SetProgressIndicator(this, progressIndicator);

            Binding binding = new Binding("IsLoading") { Source = _viewModel };
            BindingOperations.SetBinding(
                progressIndicator, ProgressIndicator.IsVisibleProperty, binding);

            binding = new Binding("IsLoading") { Source = _viewModel };
            BindingOperations.SetBinding(
                progressIndicator, ProgressIndicator.IsIndeterminateProperty, binding);

            progressIndicator.Text = "Loading streams...";

            _pageNumber = 0;

            _viewModel.LoadPage(App.ViewModel.curTopGame.game.name, _pageNumber++);
        }
        public TrackList()
        {
            InitializeComponent();
            #if DEBUG
            //adDuplexControl.IsTest = true;
            #endif
            proindicator = new ProgressIndicator();
            SystemTray.SetProgressIndicator(this, proindicator);

            back_worker = new BackgroundWorker();
            search = new BackgroundWorker();
            addvideo_worker = new BackgroundWorker();
            delvideo_worker = new BackgroundWorker();
            delplay_worker = new BackgroundWorker();

            back_worker.DoWork += new DoWorkEventHandler(back_worker_DoWork);
            back_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(back_worker_RunWorkerCompleted);
            search.DoWork += new DoWorkEventHandler(search_DoWork);
            search.RunWorkerCompleted += new RunWorkerCompletedEventHandler(search_RunWorkerCompleted);
            addvideo_worker.DoWork += new DoWorkEventHandler(addvideo_worker_DoWork);
            addvideo_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(addvideo_worker_RunWorkerCompleted);
            delvideo_worker.DoWork += new DoWorkEventHandler(delvideo_worker_DoWork);
            delvideo_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delvideo_worker_RunWorkerCompleted);
            delplay_worker.DoWork += new DoWorkEventHandler(delplay_worker_DoWork);
            delplay_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delplay_worker_RunWorkerCompleted);
            progrss_report = new ProgressReporter();
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            try
            {
                duesModel = new DuesPortableModel();

                //(App.Current as App).SecondPageObject = null;
                progressIndicator = SystemTray.ProgressIndicator;
                progressIndicator = new ProgressIndicator();
                SystemTray.SetProgressIndicator(this, progressIndicator);
                progressIndicator.IsIndeterminate = true;
                progressIndicator.Text = "Pulling Dues...";
                if (SettingsMobile.Instance.User == null)
                {
                    SqlFactory fact = new SqlFactory();
                    SettingsMobile.Instance.User = fact.GetProfile();
                }
                if (SettingsMobile.Instance.AccountSettings.IsTreasurer)
                {
                    ApplicationBar.IsVisible = true;
                }
            }
            catch (Exception exception)
            {
                ErrorHandler.Save(exception, MobileTypeEnum.WP8);
            }


            PullDues();
        }
Example #14
0
        private void SearchPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.GamesList.ItemsSource = _viewModel.GameList;
            this.StreamsList.ItemsSource = _viewModel.StreamList;

            this.StreamsList.SelectedItem = null;
            this.GamesList.SelectedItem = null;

            this.StreamsSearchBox.Text = "Search...";
            this.GamesSearchBox.Text = "Search...";

            var progressIndicator = SystemTray.ProgressIndicator;
            if (progressIndicator != null)
            {
                return;
            }

            progressIndicator = new ProgressIndicator();

            SystemTray.SetProgressIndicator(this, progressIndicator);

            Binding binding = new Binding("IsLoading") { Source = _viewModel };
            BindingOperations.SetBinding(
                progressIndicator, ProgressIndicator.IsVisibleProperty, binding);

            binding = new Binding("IsLoading") { Source = _viewModel };
            BindingOperations.SetBinding(
                progressIndicator, ProgressIndicator.IsIndeterminateProperty, binding);

            progressIndicator.Text = "Loading streams...";
        }
Example #15
0
        public void show(string options)
        {
            string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
            string title = args[0];
            string message = args[1];

            if (message == null)
            {
                message = title;
            }

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {

                if (progressIndicator == null)
                {
                    progressIndicator = new ProgressIndicator() { IsIndeterminate = true };
                }
                progressIndicator.Text = message;
                progressIndicator.IsVisible = true;

                if (page == null)
                {
                    page = (Application.Current.RootVisual as PhoneApplicationFrame).Content as PhoneApplicationPage;
                }

                SystemTray.SetProgressIndicator(page, progressIndicator);

            });
        }
Example #16
0
        /// <summary>
        /// Constructor
        /// </summary>
        public PageSettings()
        {
            InitializeComponent();

            SystemTray.SetIsVisible(this, false);
            SystemTray.SetOpacity(this, 0.5);
            progressIndicator = new ProgressIndicator();
            progressIndicator.IsVisible = false;
            progressIndicator.IsIndeterminate = true;
            progressIndicator.Text = "Loading...";
            SystemTray.SetProgressIndicator(this, progressIndicator);

            this.connection = (Application.Current as App).Connection;
            // TODO voisi toteuttaa TryGetValuella?
            if (IsolatedStorageSettings.ApplicationSettings.Contains("savepassword"))
                checkBoxSavePassword.IsChecked = (bool)IsolatedStorageSettings.ApplicationSettings["savepassword"];
            if (IsolatedStorageSettings.ApplicationSettings.Contains("autoconnect"))
                checkBoxAutoConnect.IsChecked = (bool)IsolatedStorageSettings.ApplicationSettings["autoconnect"];
            if (IsolatedStorageSettings.ApplicationSettings.Contains("testmode"))
                checkBoxTestMode.IsChecked = (bool)IsolatedStorageSettings.ApplicationSettings["testmode"];
            if (IsolatedStorageSettings.ApplicationSettings.Contains("server"))
                textBoxServer.Text = (string)IsolatedStorageSettings.ApplicationSettings["server"];
            if (IsolatedStorageSettings.ApplicationSettings.Contains("port"))
                textBoxPort.Text = (int)IsolatedStorageSettings.ApplicationSettings["port"] + "";
            if (IsolatedStorageSettings.ApplicationSettings.Contains("password"))
                passwordBoxPassword.Password = (string)IsolatedStorageSettings.ApplicationSettings["password"];

            buttonDisconnect.IsEnabled = this.connection.IsConnected;
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            try
            {
                ev = new CalendarEventPortable();
                var ob = (App.Current as App).SecondPageObject;
                if (ob != null)
                    ev = (CalendarEventPortable)ob;
                (App.Current as App).SecondPageObject = null;
                progressIndicator = SystemTray.ProgressIndicator;
                progressIndicator = new ProgressIndicator();
                SystemTray.SetProgressIndicator(this, progressIndicator);
                progressIndicator.IsIndeterminate = true;
                progressIndicator.Text = "Saving Checkin...";
                if (SettingsMobile.Instance.User == null)
                {
                    SqlFactory fact = new SqlFactory();
                    SettingsMobile.Instance.User = fact.GetProfile();
                }
                CheckInTypeSelect.ItemsSource = CalendarEventPointTypeEnumHelper.CalendarEventPointTypes;
                ev.CalendarItemId = new Guid(this.NavigationContext.QueryString["evId"]);
                ev.CalendarId = new Guid(this.NavigationContext.QueryString["calId"]);
                ev.Name = this.NavigationContext.QueryString["name"];
                if (!String.IsNullOrEmpty(ev.Name))
                    EventName.Text = ev.Name;
            }
            catch (Exception exception)
            {
                ErrorHandler.Save(exception, MobileTypeEnum.WP8);
            }

        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            try
            {
                if (e.NavigationMode == NavigationMode.New)
                {
                    dues = new DuesPortableModel();
                    //(App.Current as App).SecondPageObject = null;
                    progressIndicator = SystemTray.ProgressIndicator;
                    progressIndicator = new ProgressIndicator();
                    SystemTray.SetProgressIndicator(this, progressIndicator);
                    progressIndicator.IsIndeterminate = true;
                    progressIndicator.Text = "Pulling Dues Settings...";
                    duesId = new Guid(this.NavigationContext.QueryString["dmid"]);
                    if (SettingsMobile.Instance.User == null)
                    {
                        SqlFactory fact = new SqlFactory();
                        SettingsMobile.Instance.User = fact.GetProfile();
                    }

                    PullTopic();
                }
            }
            catch (Exception exception)
            {
                ErrorHandler.Save(exception, MobileTypeEnum.WP8);
            }
        }
        public AddPost()
        {
            InitializeComponent();
            try
            {
                progressIndicator = SystemTray.ProgressIndicator;
                progressIndicator = new ProgressIndicator();

                SystemTray.SetProgressIndicator(this, progressIndicator);
                progressIndicator.IsIndeterminate = true;
                progressIndicator.Text = "Pulling Categories...";

                forumModel = (ForumModel)(App.Current as App).SecondPageObject;
                Groups.ItemsSource = forumModel.Groups;
                currentGroup = forumModel.Groups.Where(x => x.GroupId == forumModel.GroupId).FirstOrDefault();
                if (currentGroup != null)
                {
                    ForumGroupName.Text = currentGroup.GroupName;
                    //groupName.Text = currentGroup.GroupName;
                    Groups.SelectedItem = currentGroup;
                    Categories.ItemsSource = currentGroup.Categories;
                }
            }
            catch (Exception exception)
            {
                ErrorHandler.Save(exception, MobileTypeEnum.WP8);
            }
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            try
            {
                members = new ObservableCollection<MemberDisplayAPI>();

                //(App.Current as App).SecondPageObject = null;
                progressIndicator = SystemTray.ProgressIndicator;
                progressIndicator = new ProgressIndicator();
                SystemTray.SetProgressIndicator(this, progressIndicator);
                progressIndicator.IsIndeterminate = true;
                progressIndicator.Text = "Pulling Members...";
                if (SettingsMobile.Instance.User == null)
                {
                    SqlFactory fact = new SqlFactory();
                    SettingsMobile.Instance.User = fact.GetProfile();
                }
            }
            catch (Exception exception)
            {
                ErrorHandler.Save(exception, MobileTypeEnum.WP8);
            }


            PullMembers();
        }
Example #21
0
        public DropBoxAuth()
        {
            InitializeComponent();

            _indicator = AddIndicator();
            _client = DropBoxUtils.Create();
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            try
            {
                conversation = new ConversationModel();

                //(App.Current as App).SecondPageObject = null;
                progressIndicator = SystemTray.ProgressIndicator;
                progressIndicator = new ProgressIndicator();
                SystemTray.SetProgressIndicator(this, progressIndicator);
                progressIndicator.IsIndeterminate = true;
                progressIndicator.Text = "Pulling Messages...";
                if (SettingsMobile.Instance.User == null)
                {
                    SqlFactory fact = new SqlFactory();
                    SettingsMobile.Instance.User = fact.GetProfile();
                }
                conversation.GroupMessageId = Convert.ToInt64(this.NavigationContext.QueryString["mid"]);
                PullTopic();

                _timer = new DispatcherTimer();
                _timer.Interval = TimeSpan.FromSeconds(20);
                _timer.Tick += (s, eee) => Tick();
                _timer.Start();
            }
            catch (Exception exception)
            {
                ErrorHandler.Save(exception, MobileTypeEnum.WP8);
            }

        }
Example #23
0
        public PageBase()
        {
            var navInTransition = new NavigationInTransition
            {
                Backward = new TurnstileTransition { Mode = TurnstileTransitionMode.BackwardIn },
                Forward = new TurnstileTransition { Mode = TurnstileTransitionMode.ForwardIn }
            };

            var navOutTransition = new NavigationOutTransition
            {
                Backward = new TurnstileTransition { Mode = TurnstileTransitionMode.BackwardOut },
                Forward = new TurnstileTransition { Mode = TurnstileTransitionMode.ForwardOut }
            };

            TransitionService.SetNavigationInTransition(this, navInTransition);
            TransitionService.SetNavigationOutTransition(this, navOutTransition);

            SetValue(TiltEffect.IsTiltEnabledProperty, true);

            Language = System.Windows.Markup.XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);

            Progress = new ProgressIndicator
            {
                IsIndeterminate = false,
                IsVisible = true
            };

            SystemTray.SetProgressIndicator(this, Progress);

            if (!DesignerProperties.IsInDesignTool)
            {
                Service = App.Service;
            }
        }
        async void GeneratePicture()
        {
            if (rendering) return;


            ProgressIndicator prog = new ProgressIndicator();
            prog.IsIndeterminate = true;
            prog.Text = "Rendering";
            prog.IsVisible = true;
            SystemTray.SetProgressIndicator(this, prog);



            var bmp = new WriteableBitmap(480, 800);
            try
            {
                rendering = true;

             
              
                using (var renderer = new WriteableBitmapRenderer(manager, bmp, OutputOption.PreserveAspectRatio))
                {
                    display.Source = await renderer.RenderAsync();
                }

                SystemTray.SetProgressIndicator(this, null);
                rendering = false;
            }
            finally
            {
               
            }


        }
Example #25
0
 protected VkPageBase()
 {
     SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;
     Orientation = PageOrientation.None;
     SystemTray.SetIsVisible(this, true);
     TransitionService.SetNavigationInTransition(
         this,
         new NavigationInTransition
             {
                 Backward = new SlideTransition {Mode = SlideTransitionMode.SlideDownFadeIn},
                 Forward = new SlideTransition {Mode = SlideTransitionMode.SlideUpFadeIn}
             });
     TransitionService.SetNavigationOutTransition(
         this,
         new NavigationOutTransition
             {
                 Backward = new SlideTransition {Mode = SlideTransitionMode.SlideDownFadeOut},
                 Forward = new SlideTransition {Mode = SlideTransitionMode.SlideUpFadeOut}
             });
     ProgressIndicator pi = new ProgressIndicator();
     SystemTray.SetProgressIndicator(this, pi);
     BindingOperations.SetBinding(pi, ProgressIndicator.TextProperty, new Binding(VkViewModelBase.StatusPropertyName));
     BindingOperations.SetBinding(pi, ProgressIndicator.IsIndeterminateProperty, new Binding(VkViewModelBase.IsStatusProgressPropertyName));
     BindingOperations.SetBinding(pi, ProgressIndicator.IsVisibleProperty, new Binding(VkViewModelBase.StatusPropertyName)
                                                                               {
                                                                                   Converter = new StringToBoolConverter()
                                                                               });
 }
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the page DataContext property to the ViewModel.
            this.DataContext = App.ViewModel;

            Pi = new ProgressIndicator();
            Pi.IsIndeterminate = true;
            Pi.IsVisible = false;

            allPivotItem = new PivotItem();
            allPivotItem.Header = new ToDoCategory { Name = "All", IconPath = "/Sticky-Notes-icon.png" };
            ListBox listbox = new ListBox();
            listbox.Margin = new Thickness(12, 0, 12, 0);
            listbox.Width = 440;
            listbox.ItemTemplate = ToDoListBoxItemTemplate;
            listbox.Tap += Parent_Tap;
            allPivotItem.Content = listbox;

            searchResult = new PivotItem();
            searchResult.Header = new ToDoCategory { Name = "Search result", IconPath = "/Images/CategoryIcons/SearchResult.png" };
            ListBox lstbox = new ListBox();
            lstbox.Margin = new Thickness(12, 0, 12, 0);
            lstbox.Width = 440;
            lstbox.ItemTemplate = ToDoListBoxItemTemplate;
            lstbox.Tap += Parent_Tap;
            searchResult.Content = lstbox;

            App.ViewModel.OnDataBaseChange += ViewModel_onDataBaseChanged;
            App.ViewModel.ReLoadData();
            //TestData();
        }
        public Connection()
        {
            InitializeComponent();

            if (!string.IsNullOrEmpty(App.CredentialStore.DefaultCredential.Host))
                this.HostInput.Text = App.CredentialStore.DefaultCredential.Host;

            if (App.CredentialStore.DefaultCredential.Port > 0) this.PortInput.Text = App.CredentialStore.DefaultCredential.Port.ToString();
            if (!string.IsNullOrEmpty(App.CredentialStore.DefaultCredential.Password)) this.PasswordInput.Password = App.CredentialStore.DefaultCredential.Password;

            this.HostInput.KeyUp += new KeyEventHandler(HostInput_KeyUp);
            this.PortInput.KeyUp += new KeyEventHandler(HostInput_KeyUp);
            this.ProfileList.SelectionChanged += new SelectionChangedEventHandler(ProfileList_SelectionChanged);
            foreach (var c in App.CredentialStore.Credentials)
            {
                this.ProfileList.Items.Add(c);
            }
            this.ProfileList.Items.Add("Add New...");
            this.ProfileList.SelectedItem = App.CredentialStore.DefaultCredential;

            SystemTray.SetIsVisible(this, true);
            SystemTray.SetOpacity(this, 0.5);
            SystemTray.SetBackgroundColor(this, SystemColors.DesktopColor);
            SystemTray.SetForegroundColor(this, SystemColors.MenuColor);

            prog = new ProgressIndicator();
            prog.IsVisible = false;
            prog.IsIndeterminate = true;
            prog.Text = "Connecting, please wait...";
            SystemTray.SetProgressIndicator(this, prog);
        }
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            try { 
            _viewModel = (EventViewModel)Resources["viewModel"];
            var progressIndicator = SystemTray.ProgressIndicator;
            if (progressIndicator != null)
            {
                return;
            }

            progressIndicator = new ProgressIndicator();

            SystemTray.SetProgressIndicator(this, progressIndicator);

            Binding binding = new Binding("IsLoading") { Source = _viewModel };
            BindingOperations.SetBinding(
                progressIndicator, ProgressIndicator.IsVisibleProperty, binding);

            binding = new Binding("IsLoading") { Source = _viewModel };
            BindingOperations.SetBinding(
                progressIndicator, ProgressIndicator.IsIndeterminateProperty, binding);

            progressIndicator.Text = "Loading event...";
            var skater  = (EventJson) (App.Current as App).SecondPageObject;
            //var skater = Json.DeserializeObject<EventJson>(json);
            _viewModel.EventPublic = skater;
            //_viewModel.LoadPage(skater.MemberId);
            }
            catch (Exception exception)
            {
                ErrorHandler.Save(exception, MobileTypeEnum.WP8);
            }
        }
 public RegisterPage()
 {
     InitializeComponent();
     progressIndicator = new ProgressIndicator();
     progressIndicator.IsIndeterminate = true;
     SystemTray.SetProgressIndicator(this, progressIndicator);
 }
        private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            SystemTray.SetIsVisible(this, true);
            SystemTray.SetOpacity(this, 0.5);

            var prog = new ProgressIndicator();
            prog.IsVisible = true;
            prog.IsIndeterminate = true;
            prog.Text = "loading...";

            SystemTray.SetProgressIndicator(this, prog);

            if (App.MainViewModel.SelectedScenario == null)
            {
                App.MainViewModel.SelectedScenario = new Scenario();
                App.MainViewModel.SelectedScenario.SwitchStates = (await HomeControllerApi.GetSwitches()).ToList();
            }
            else if (App.MainViewModel.SelectedScenario.StationToPlay != null)
            {
                var candidate = from r in lpRadioStations.ItemsSource as ObservableCollection<PandoraRadioStation>
                                where string.Compare(r.Id, App.MainViewModel.SelectedScenario.StationToPlay.Id, StringComparison.InvariantCultureIgnoreCase) == 0
                                select r;

                if (candidate.Count() > 0)
                    lpRadioStations.SelectedItem = candidate.First();
            }

            SystemTray.ProgressIndicator.IsVisible = false;
        }
 public void StopProgressNotification()
 {
     progress.IsVisible           = false;
     progress                     = null;
     SystemTray.ProgressIndicator = null;
 }
        public async Task <StorageFile> GetLiveEarthPictureForShowing(CancellationTokenSource source, ProgressIndicator indicator = null)
        {
            var imageID = await GetImageID(source);

            return(await DownloadImageAsync(source, imageID, indicator));
        }
        private void btnCreatePackage_Click(object sender, EventArgs e)
        {
            if (sfdSavePackage.ShowDialog() == DialogResult.OK)
            {
                string curDir = Directory.GetCurrentDirectory();

                IProgressIndicator ind = ProgressIndicator.CreateProgressIndicator(panelProgress);
                ind.SetProgress("Running Preparations.", 0, 2);
                if (cbExport.Checked)
                {
                    IProgressIndicator preps = ind.CreateSubTask(false);
                    preps.SetProgress("Copying Folder Contents...", 0, 1);

                    string dir = Path.Combine(
                        Path.GetDirectoryName(Directory.GetCurrentDirectory()),
                        "temp_" +
                        Path.GetFileNameWithoutExtension(Directory.GetCurrentDirectory())
                        );
                    CopyDirectory(Directory.GetCurrentDirectory(), dir, preps.CreateSubTask(false));
                    Directory.SetCurrentDirectory(dir);
                    string[] files = Directory.GetFiles(dir, "*.fl", SearchOption.AllDirectories);
                    preps.SetProgress("Exporting FL Scripts..", 0, 1);
                    IProgressIndicator fl2flc  = ind.CreateSubTask(false);
                    IProgressIndicator fl2flcf = fl2flc.CreateSubTask(false);
                    for (int i = 0; i < files.Length; i++)
                    {
                        string file = files[i];

                        fl2flc.SetProgress("Exporting File:" + file, i, files.Length);
                        fl2flcf.SetProgress("Parsing..", 0, 1);
                        Editor.Path = file;
                        Editor.FLContainer.SerializedProgram = null;

                        //Editor.InitProgram();
                        Editor.Build();
                        if (Editor.FLContainer.SerializedProgram == null)
                        {
                            return;
                        }

                        fl2flcf.SetProgress("Exporting..", 1, 1);
                        string f      = file + "c";
                        Stream stream = File.OpenWrite(f);
                        FLSerializer.SaveProgram(
                            stream,
                            Editor.FLContainer.SerializedProgram,
                            Editor.FLContainer.InstructionSet,
                            new string[0]
                            );
                        stream.Close();
                        if (!cbKeepFlScripts.Checked)
                        {
                            File.Delete(file);
                        }
                    }

                    fl2flcf.Dispose();
                    fl2flc.Dispose();
                    preps.Dispose();
                }

                ind.SetProgress("Creating Package.", 1, 2);
                ProgressIndicator.RunTask(
                    indicator => ResourceManager.Create(
                        Directory.GetCurrentDirectory(),
                        sfdSavePackage.FileName,
                        tbPackageName.Text,
                        tbUnpackConfig.Text,
                        indicator
                        ),
                    panelProgress,
                    Application.DoEvents,
                    ind.CreateSubTask(false)
                    );

                ind.SetProgress("Cleaning Up.", 2, 2);
                string oldDir = Directory.GetCurrentDirectory();
                Directory.SetCurrentDirectory(curDir);
                if (cbExport.Checked)
                {
                    Directory.Delete(oldDir, true);
                }

                Close();
                ind.Dispose();
            }
        }
Example #34
0
        /// <summary>
        /// Fill sheet rows for Impact sheet
        /// </summary>
        /// <returns>COBieSheet</returns>
        public override COBieSheet<COBieImpactRow> Fill()
        {
            ProgressIndicator.ReportMessage("Starting Impacts...");

            //create new sheet
            COBieSheet<COBieImpactRow> impacts = new COBieSheet<COBieImpactRow>(Constants.WORKSHEET_IMPACT);

            // get all IfcPropertySet objects from IFC file

            IEnumerable<IfcPropertySet> ifcProperties = Model.Instances.OfType<IfcPropertySet>().Where(ps => ps.Name.ToString() == "Pset_EnvironmentalImpactValues");

            ProgressIndicator.Initialise("Creating Impacts", ifcProperties.Count());

            foreach (IfcPropertySet propSet in ifcProperties)
            {
                ProgressIndicator.IncrementAndUpdate();

                COBieImpactRow impact = new COBieImpactRow(impacts);
                List<IfcSimpleProperty> propertyList = propSet.HasProperties.OfType<IfcSimpleProperty>().ToList();
                
                Interval propValues = GetPropertyValue(propertyList, "ImpactName");
                impact.Name = (propValues.Value == DEFAULT_STRING) ? propSet.Name.ToString() : propValues.Value.ToString();

                impact.CreatedBy = GetTelecomEmailAddress(propSet.OwnerHistory);
                impact.CreatedOn = GetCreatedOnDateAsFmtString(propSet.OwnerHistory);

                propValues = GetPropertyValue(propertyList, "ImpactType");
                impact.ImpactType = propValues.Value;

                propValues = GetPropertyValue(propertyList, "ImpactStage");
                impact.ImpactStage = propValues.Value;

                IfcRoot ifcRoot = GetAssociatedObject(propSet);
                impact.SheetName = GetSheetByObjectType(ifcRoot.GetType());
                impact.RowName = (!string.IsNullOrEmpty(ifcRoot.Name.ToString())) ? ifcRoot.Name.ToString() : DEFAULT_STRING;

                propValues = GetPropertyValue(propertyList, "Value");
                impact.Value = propValues.Value;
                impact.ImpactUnit = propValues.Unit;

                propValues = GetPropertyValue(propertyList, "LeadInTime");
                impact.LeadInTime = propValues.Value;

                propValues = GetPropertyValue(propertyList, "Duration");
                impact.Duration = propValues.Value;

                propValues = GetPropertyValue(propertyList, "LeadOutTime");
                impact.LeadOutTime = propValues.Value;

                impact.ExtSystem = GetExternalSystem(propSet);
                impact.ExtObject = propSet.GetType().Name;
                impact.ExtIdentifier = propSet.GlobalId;

                impact.Description = (propSet.Description != null) ? propSet.Description.ToString() : DEFAULT_STRING;

                impacts.AddRow(impact);
            }

            impacts.OrderBy(s => s.Name);

            ProgressIndicator.Finalise();

            return impacts;
        }
        /// <summary>
        /// Fill sheet rows for System sheet
        /// </summary>
        /// <returns>COBieSheet</returns>
        public COBieSheet <COBieSystemRow> Fill(Dictionary <string, HashSet <string> > compIndices)
        {
            ProgressIndicator.ReportMessage("Starting Systems...");

            //Create new sheet
            COBieSheet <COBieSystemRow> systems = new COBieSheet <COBieSystemRow>(Constants.WORKSHEET_SYSTEM);

            // get all IfcSystem, IfcGroup and IfcElectricalCircuit objects from IFC file
            IEnumerable <IfcGroup> ifcGroups = Model.FederatedInstances.OfType <IfcGroup>().Where(ifcg => ifcg is IfcSystem); //get anything that is IfcSystem or derived from it eg IfcElectricalCircuit
            //IEnumerable<IfcSystem> ifcSystems = Model.FederatedInstances.OfType<IfcSystem>();
            //IEnumerable<IfcElectricalCircuit> ifcElectricalCircuits = Model.FederatedInstances.OfType<IfcElectricalCircuit>();
            //ifcGroups = ifcGroups.Union(ifcSystems);
            //ifcGroups = ifcGroups.Union(ifcElectricalCircuits);

            //Alternative method of extraction
            List <string> PropertyNames = new List <string> {
                "Circuit Number", "System Name"
            };

            IEnumerable <IfcPropertySet> ifcPropertySets = from ps in Model.FederatedInstances.OfType <IfcPropertySet>()
                                                           from psv in ps.HasProperties.OfType <IfcPropertySingleValue>()
                                                           where PropertyNames.Contains(psv.Name)
                                                           select ps;

            ProgressIndicator.Initialise("Creating Systems", ifcGroups.Count() + ifcPropertySets.Count());

            foreach (IfcGroup ifcGroup in ifcGroups)
            {
                ProgressIndicator.IncrementAndUpdate();

                IEnumerable <IfcProduct> ifcProducts = (ifcGroup.IsGroupedBy == null) ? Enumerable.Empty <IfcProduct>() : ifcGroup.IsGroupedBy.RelatedObjects.OfType <IfcProduct>();

                foreach (IfcProduct product in ifcProducts)
                {
                    COBieSystemRow sys = new COBieSystemRow(systems);

                    sys.Name = ifcGroup.Name;

                    sys.CreatedBy = GetTelecomEmailAddress(ifcGroup.OwnerHistory);
                    sys.CreatedOn = GetCreatedOnDateAsFmtString(ifcGroup.OwnerHistory);

                    sys.Category = GetCategory(ifcGroup);
                    string name = product.Name;
                    if (string.IsNullOrEmpty(product.Name) || (product.Name == Constants.DEFAULT_STRING))
                    {
                        name = product.GetType().Name + " Name Unknown " + UnknownCount.ToString();
                        UnknownCount++;
                    }
                    else
                    {
                        if (compIndices.Count > 0) //check we have values
                        {
                            //check for name in components , if missing exclude from system, unknown names are listed see above
                            if (!compIndices["Name"].Contains(name, StringComparer.OrdinalIgnoreCase))
                            {
                                continue;
                            }
                        }
                    }
                    sys.ComponentNames = product.Name;
                    sys.ExtSystem      = GetExternalSystem(ifcGroup);
                    sys.ExtObject      = ifcGroup.GetType().Name; //need to create product if filtered out in the components sheet
                    if (!string.IsNullOrEmpty(ifcGroup.GlobalId))
                    {
                        sys.ExtIdentifier = ifcGroup.GlobalId;//need to create product if filtered out in the components sheet
                    }
                    sys.Description = GetSystemDescription(ifcGroup);

                    systems.AddRow(sys);
                }
                //check if no products then add group only, new line for each, or should we do as assembly? conCant with :
                if (!ifcProducts.Any())
                {
                    COBieSystemRow sys = new COBieSystemRow(systems);

                    sys.Name = ifcGroup.Name;

                    sys.CreatedBy = GetTelecomEmailAddress(ifcGroup.OwnerHistory);
                    sys.CreatedOn = GetCreatedOnDateAsFmtString(ifcGroup.OwnerHistory);

                    sys.Category       = GetCategory(ifcGroup);
                    sys.ComponentNames = DEFAULT_STRING;
                    sys.ExtSystem      = GetExternalSystem(ifcGroup);
                    sys.ExtObject      = ifcGroup.GetType().Name;
                    if (!string.IsNullOrEmpty(ifcGroup.GlobalId))
                    {
                        sys.ExtIdentifier = ifcGroup.GlobalId;
                    }
                    sys.Description = GetSystemDescription(ifcGroup);

                    systems.AddRow(sys);
                }
            }


            foreach (IfcPropertySet ifcPropertySet in ifcPropertySets)
            {
                ProgressIndicator.IncrementAndUpdate();
                string name = "";
                IfcRelDefinesByProperties ifcRelDefinesByProperties = ifcPropertySet.PropertyDefinitionOf.FirstOrDefault(); //one or zero
                IfcPropertySingleValue    ifcPropertySingleValue    = ifcPropertySet.HasProperties.OfType <IfcPropertySingleValue>().Where(psv => PropertyNames.Contains(psv.Name)).FirstOrDefault();
                if ((ifcPropertySingleValue != null) && (ifcPropertySingleValue.NominalValue != null) && (!string.IsNullOrEmpty(ifcPropertySingleValue.NominalValue.ToString())))
                {
                    name = ifcPropertySingleValue.NominalValue.ToString();
                }
                else //try for "System Classification" Not in matrix but looks a good candidate
                {
                    IfcPropertySingleValue ifcPropertySVClassification = ifcPropertySet.HasProperties.OfType <IfcPropertySingleValue>().Where(psv => psv.Name == "System Classification").FirstOrDefault();
                    if ((ifcPropertySVClassification != null) && (ifcPropertySVClassification.NominalValue != null) && (!string.IsNullOrEmpty(ifcPropertySVClassification.NominalValue.ToString())))
                    {
                        name = ifcPropertySVClassification.NominalValue.ToString();
                    }
                }

                foreach (IfcObject ifcObject in ifcRelDefinesByProperties.RelatedObjects)
                {
                    if (ifcObject != null)
                    {
                        COBieSystemRow sys = new COBieSystemRow(systems);
                        //OK if we have no name lets just guess at the first value as we need a value
                        if (string.IsNullOrEmpty(name))
                        {
                            //get first text value held in NominalValue
                            var names = ifcPropertySet.HasProperties.OfType <IfcPropertySingleValue>().Where(psv => (psv.NominalValue != null) && (!string.IsNullOrEmpty(psv.NominalValue.ToString()))).Select(psv => psv.NominalValue).FirstOrDefault();
                            if (names != null)
                            {
                                name = names.ToString();
                            }
                            else
                            {
                                //OK last chance, lets take the property name that is not in the filter list of strings, ie. != "Circuit Number", "System Name" or "System Classification" from above
                                IfcPropertySingleValue propname = ifcPropertySet.HasProperties.OfType <IfcPropertySingleValue>().Where(psv => !PropertyNames.Contains(psv.Name)).FirstOrDefault();
                                if (propname != null)
                                {
                                    name = propname.Name.ToString();
                                }
                            }
                        }
                        sys.Name = string.IsNullOrEmpty(name) ? DEFAULT_STRING : name;

                        sys.CreatedBy = GetTelecomEmailAddress(ifcObject.OwnerHistory);
                        sys.CreatedOn = GetCreatedOnDateAsFmtString(ifcObject.OwnerHistory);

                        sys.Category = (ifcPropertySingleValue.Name == "Circuit Number") ? "circuit" : GetCategory(ifcObject); //per matrix v9
                        //check that the element is in the component list
                        if (compIndices.Count > 0)                                                                             //check we have values
                        {
                            //check for name in components , if missing exclude from system, unknown names are listed see above
                            if (!compIndices["Name"].Contains(ifcObject.Name.ToString(), StringComparer.OrdinalIgnoreCase))
                            {
                                continue;
                            }
                        }
                        sys.ComponentNames = ifcObject.Name;
                        sys.ExtSystem      = GetExternalSystem(ifcPropertySet);
                        sys.ExtObject      = ifcPropertySingleValue.GetType().Name;
                        sys.Description    = string.IsNullOrEmpty(name) ? DEFAULT_STRING : name;;

                        systems.AddRow(sys);
                    }
                }
            }

            systems.OrderBy(s => s.Name);

            ProgressIndicator.Finalise();
            return(systems);
        }
        private async Task <StorageFile> DownloadImageAsync(CancellationTokenSource source, string imageID, ProgressIndicator indicator)
        {
            if (imageID != null)
            {
                StorageFile savedImage = await GetSavedPureImageByIDAsync(imageID);

                if (savedImage != null)
                {
                    return(savedImage);
                }
                if (await SaveImage(source, imageID, indicator) == 0)
                {
                    Config.Instance.SetLastImageID(imageID);
                    return(await BlitEarthImageAsync(imageID));
                }
            }
            return(null);
        }
Example #37
0
        /// <summary>
        /// Takes an input fasta file and writes a target-decoy database
        /// </summary>
        /// <param name="fastaDB">The input database</param>
        /// <param name="nameOut">If not null, indicates the ouput filename</param>
        public static void ReverseDecoy(string fastaDB, string outputFile = null)
        {
            Console.WriteLine("Reading FASTA file");
            List <string>     fasta    = File.ReadAllLines(fastaDB).ToList();
            List <char>       sequence = new List <char>();
            string            decoy    = "DECOY_";
            string            decoy_header;
            int               width = 60;
            string            nameOut;
            ProgressIndicator P = new ProgressIndicator(fasta.Count() * 2, "Writing target-decoy database");

            if (outputFile == null)
            {
                nameOut = fastaDB + ".TARGET_DECOY.fasta";
            }
            else
            {
                nameOut = outputFile;
            }
            P.Start();

            using (StreamWriter f = new StreamWriter(nameOut))
            {
                // first write the forward DB
                foreach (string line in fasta)
                {
                    f.WriteLine(line);
                    P.Update();
                }

                // now for the decoy

                // Write the first line
                f.Write(fasta[0]);
                // remove it
                fasta.RemoveAt(0);

                foreach (string line in fasta)
                {
                    if (line[0] == '>')
                    {
                        // the line is the next header, before writing it we need to reverse and write the sequence of the previous protein
                        sequence.Reverse();
                        for (int i = 0; i < sequence.Count(); i++)
                        {
                            if (i % width == 0)
                            {
                                f.Write('\n');
                            }
                            f.Write(sequence[i]);
                        }
                        f.Write('\n');

                        // add DECOY_ to the header
                        decoy_header = line.Insert(1, decoy);

                        // write the header
                        f.Write(decoy_header);

                        // erase the current sequence
                        sequence = new List <char>();
                    }
                    else
                    {
                        // the line is not a header, so add it to the sequence list
                        foreach (var aa in line)
                        {
                            sequence.Add(aa);
                        }
                    }
                    P.Update();
                }
                P.Done();
            }
        }
        internal static void Migrate()
        {
            ProgressIndicator progressIndicator = new ProgressIndicator(Migrate_BackgroundEventHandler, "Migrating Uprating Indices ...");

            progressIndicator.ShowDialog();
        }
 protected override void OnCharProcessed(char ch)
 {
     ProgressIndicator.Increment(1);
 }
Example #40
0
        protected void TestExtremelyLong()
        {
            const int   SLEEP_TIME_MS   = 10;
            int         THREADS         = System.Environment.ProcessorCount;
            const float TARGET_CPU_LOAD = 0.4f;

            Assert.IsTrue(THREADS <= System.Environment.ProcessorCount);

            ProgressIndicator pi = new ProgressIndicator("Crypto +4GB Test");

            pi.AddLine(String.Format("Configuration: {0} threads, CPU Load: {1}%", THREADS, TARGET_CPU_LOAD * 100));

            CancellationTokenSource src = new CancellationTokenSource();

            Task regulator = Task.Factory.StartNew(token =>
            {
                PerformanceCounter pc = new PerformanceCounter("Processor", "% Processor Time", "_Total");

                List <float> cpu_load = new List <float>();

                for (;;)
                {
                    const int PROBE_DELTA_MS = 200;
                    const int PROBE_COUNT    = 30;
                    const int REGULATE_COUNT = 10;

                    for (int i = 0; i < REGULATE_COUNT; i++)
                    {
                        System.Threading.Thread.Sleep(PROBE_DELTA_MS);

                        cpu_load.Add(pc.NextValue() / 100);

                        if (src.IsCancellationRequested)
                        {
                            break;
                        }
                    }

                    while (cpu_load.Count > PROBE_COUNT)
                    {
                        cpu_load.RemoveFirst();
                    }

                    int old_transform_rounds = transform_rounds;

                    float avg_cpu_load = cpu_load.Average();

                    if (avg_cpu_load >= TARGET_CPU_LOAD)
                    {
                        transform_rounds = (int)Math.Round(transform_rounds * 0.9);

                        if (old_transform_rounds == transform_rounds)
                        {
                            transform_rounds--;
                        }
                    }
                    else
                    {
                        transform_rounds = (int)Math.Round(transform_rounds * 1.1);

                        if (old_transform_rounds == transform_rounds)
                        {
                            transform_rounds++;
                        }
                    }

                    if (transform_rounds == 0)
                    {
                        transform_rounds = 1;
                    }

                    if (src.IsCancellationRequested)
                    {
                        break;
                    }
                }
            }, src.Token);

            var partitioner = Partitioner.Create(Hashes.CryptoAll, EnumerablePartitionerOptions.None);

            Parallel.ForEach(partitioner, new ParallelOptions()
            {
                MaxDegreeOfParallelism = THREADS
            }, ht =>
            {
                IHash hash = (IHash)Activator.CreateInstance(ht);

                pi.AddLine(String.Format("{0} / {1} - {2} - {3}%", Hashes.CryptoAll.IndexOf(ht) + 1,
                                         Hashes.CryptoAll.Count, hash.Name, 0));

                TestData test_data = TestData.Load(hash);

                int test_data_index = 0;

                for (int i = 0; i < test_data.Count; i++)
                {
                    if (test_data.GetRepeat(i) == 1)
                    {
                        continue;
                    }

                    test_data_index++;

                    ulong repeats          = (ulong)test_data.GetRepeat(i);
                    byte[] data            = test_data.GetData(i);
                    string expected_result = Converters.ConvertBytesToHexString(test_data.GetHash(i));

                    hash.Initialize();

                    int transform_counter = transform_rounds;
                    DateTime progress     = DateTime.Now;

                    for (ulong j = 0; j < repeats; j++)
                    {
                        hash.TransformBytes(data);

                        transform_counter--;
                        if (transform_counter == 0)
                        {
                            System.Threading.Thread.Sleep(SLEEP_TIME_MS);
                            transform_counter = transform_rounds;
                        }

                        if (DateTime.Now - progress > TimeSpan.FromSeconds(5))
                        {
                            pi.AddLine(String.Format("{0} / {1} / {2} - {3} - {4}%", Hashes.CryptoAll.IndexOf(ht) + 1,
                                                     test_data_index, Hashes.CryptoAll.Count, hash.Name, j * 100 / repeats));
                            progress = DateTime.Now;
                        }
                    }

                    HashResult result = hash.TransformFinal();

                    Assert.AreEqual(expected_result, Converters.ConvertBytesToHexString(result.GetBytes()), hash.ToString());

                    pi.AddLine(String.Format("{0} / {1} / {2} - {3} - {4}", Hashes.CryptoAll.IndexOf(ht) + 1,
                                             test_data_index, Hashes.CryptoAll.Count, hash.Name, "OK"));
                }
            });

            src.Cancel();
            regulator.Wait();
        }
Example #41
0
 protected override void OnLinePorcessed(string line)
 {
     ProgressIndicator.Increment(1);
 }
        private async Task <int> SaveImage(CancellationTokenSource _source, string imageID, ProgressIndicator indicator)
        {
            WebClient client = new WebClient();

            _source.Token.Register(client.CancelAsync);
            try
            {
                for (int ii = 0; ii < size; ii++)
                {
                    for (int jj = 0; jj < size; jj++)
                    {
                        string url         = string.Format("{0}/{1}d/550/{2}_{3}_{4}.png", imageSource, size, imageID, ii, jj);
                        string image_name  = string.Format("{0}_{1}.png", ii, jj); // remove the '/' in imageID
                        var    destination = await ApplicationData.Current.LocalFolder.CreateFileAsync(image_name, CreationCollisionOption.ReplaceExisting);

                        await client.DownloadFileTaskAsync(url, destination.Path);

                        if (indicator != null)
                        {
                            indicator(jj + 1 + ii * Convert.ToInt32(size), Convert.ToInt32(size * size));
                        }
                    }
                }
                return(0);
            }
            catch (Exception e)
            {
                return(-1);
            }
        }
Example #43
0
    private void MakeFont(ProgressIndicator progressIndicator)
    {
        progressIndicator.Show("Process font images...");
        List <Texture2D> list = new List <Texture2D>();

        FontMaker.Font[] array = this.fonts;
        for (int i = 0; i < array.Length; i++)
        {
            FontMaker.Font     font   = array[i];
            FontMaker.Glyphs[] array2 = font.GetGlyphs();
            for (int j = 0; j < array2.Length; j++)
            {
                FontMaker.Glyphs glyphs = array2[j];
                if (glyphs.GetTexture() == null)
                {
                    Debug.LogErrorFormat("The font {0} with graph: {1} is missing texture.", new object[]
                    {
                        font.GetFontName(),
                        glyphs.GetCode()
                    });
                }
                else
                {
                    string          assetPath       = AssetDatabase.GetAssetPath(glyphs.GetTexture());
                    TextureImporter textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter;
                    if (textureImporter != null)
                    {
                        bool flag = false;
                        if (!textureImporter.isReadable)
                        {
                            textureImporter.isReadable = true;
                            flag = true;
                        }
                        if (textureImporter.textureCompression != TextureImporterCompression.Uncompressed)
                        {
                            textureImporter.textureCompression = TextureImporterCompression.Uncompressed;
                            flag = true;
                        }
                        if (textureImporter.mipmapEnabled)
                        {
                            textureImporter.mipmapEnabled = false;
                            flag = true;
                        }
                        if (textureImporter.npotScale != TextureImporterNPOTScale.None)
                        {
                            textureImporter.npotScale = TextureImporterNPOTScale.None;
                            flag = true;
                        }
                        if (flag)
                        {
                            textureImporter.SaveAndReimport();
                        }
                    }
                    list.Add(glyphs.GetTexture());
                }
            }
        }
        progressIndicator.SetProgress(0.25f);
        progressIndicator.Show("Build font atlas...");
        Texture2D texture2D = new Texture2D(0, 0, TextureFormat.ARGB32, false);

        texture2D.name = "Font Atlas";
        Rect[] array3        = texture2D.PackTextures(list.ToArray(), this.padding, this.maximumAtlasSize, false);
        string assetPath2    = AssetDatabase.GetAssetPath(this);
        string directoryName = Path.GetDirectoryName(assetPath2);
        string text          = this.atlasName;

        if (!text.EndsWith(".png") || !text.EndsWith(".PNG"))
        {
            text += ".png";
        }
        string text2 = Path.Combine(directoryName, text);

        byte[]     array4     = ImageConversion.EncodeToPNG(texture2D);
        FileStream fileStream = File.OpenWrite(text2);

        fileStream.Write(array4, 0, array4.Length);
        fileStream.Close();
        AssetDatabase.Refresh();
        TextureImporter textureImporter2 = AssetImporter.GetAtPath(text2) as TextureImporter;

        if (textureImporter2 != null)
        {
            bool flag2 = false;
            if (textureImporter2.isReadable)
            {
                textureImporter2.isReadable = false;
                flag2 = true;
            }
            if (!textureImporter2.alphaIsTransparency)
            {
                textureImporter2.alphaIsTransparency = true;
                flag2 = true;
            }
            if (flag2)
            {
                textureImporter2.SaveAndReimport();
            }
        }
        Texture mainTexture = AssetDatabase.LoadAssetAtPath <Texture>(text2);

        progressIndicator.SetProgress(0.35f);
        progressIndicator.Show("Build font material...");
        string   path     = this.atlasName + ".mat";
        string   text3    = Path.Combine(directoryName, path);
        Material material = AssetDatabase.LoadAssetAtPath <Material>(text3);

        if (material == null)
        {
            Shader shader = Shader.Find("Transparent/Diffuse");
            material = new Material(shader);
            AssetDatabase.CreateAsset(material, text3);
        }
        material.mainTexture = mainTexture;
        EditorUtility.SetDirty(material);
        AssetDatabase.SaveAssets();
        progressIndicator.SetProgress(0.7f);
        progressIndicator.Show("Build font settings...");
        int num = 0;

        FontMaker.Font[] array5 = this.fonts;
        for (int k = 0; k < array5.Length; k++)
        {
            FontMaker.Font     font2  = array5[k];
            FontMaker.Glyphs[] array6 = font2.GetGlyphs();
            if (array6.Length != 0)
            {
                string text4 = font2.GetFontName();
                if (!text4.EndsWith(".fontsettings"))
                {
                    text4 += ".fontsettings";
                }
                string           text5 = Path.Combine(directoryName, text4);
                UnityEngine.Font font  = AssetDatabase.LoadAssetAtPath <UnityEngine.Font>(text5);
                if (font == null)
                {
                    font = new UnityEngine.Font();
                    AssetDatabase.CreateAsset(font, text5);
                }
                float           num2   = 0f;
                CharacterInfo[] array7 = new CharacterInfo[array6.Length];
                for (int l = 0; l < array6.Length; l++)
                {
                    FontMaker.Glyphs glyphs2    = array6[l];
                    Texture2D        texture2D2 = glyphs2.GetTexture();
                    Rect             rect       = array3[num++];
                    if (num2 < (float)texture2D2.height)
                    {
                        num2 = (float)texture2D2.height;
                    }
                    CharacterInfo characterInfo = default(CharacterInfo);
                    characterInfo.index = glyphs2.GetCode();
                    float x      = rect.x;
                    float y      = rect.y;
                    float width  = rect.width;
                    float height = rect.height;
                    characterInfo.uvBottomLeft  = new Vector2(x, y);
                    characterInfo.uvBottomRight = new Vector2(x + width, y);
                    characterInfo.uvTopLeft     = new Vector2(x, y + height);
                    characterInfo.uvTopRight    = new Vector2(x + width, y + height);
                    characterInfo.minX          = 0;
                    characterInfo.minY          = -texture2D2.height;
                    characterInfo.maxX          = texture2D2.width;
                    characterInfo.maxY          = 0;
                    characterInfo.advance       = texture2D2.width;
                    array7[l] = characterInfo;
                }
                font.characterInfo = array7;
                font.material      = material;
                SerializedObject serializedObject = new SerializedObject(font);
                serializedObject.Update();
                SerializedProperty serializedProperty = serializedObject.FindProperty("m_LineSpacing");
                serializedProperty.floatValue = num2;
                serializedObject.ApplyModifiedPropertiesWithoutUndo();
                EditorUtility.SetDirty(font);
            }
        }
        progressIndicator.SetProgress(0.95f);
        progressIndicator.Show("Save and refresh assets.");
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
 public void Initialize(PhoneApplicationFrame frame)
 {
     _progressIndicator = new ProgressIndicator();
     frame.Navigated   += OnRootFrameNavigated;
 }
        /// <summary>
        /// Fill sheet rows for Coordinate sheet
        /// </summary>
        public override COBieSheet <COBieCoordinateRow> Fill()
        {
            //get the conversion to the COBie units (metres or feet)
            double conversionFactor;
            var    cobieUnits = Context.WorkBookUnits.LengthUnit.ToLowerInvariant();

            if (cobieUnits == "meters" || cobieUnits == "metres")
            {
                conversionFactor = Model.ModelFactors.OneMetre;
            }
            else if (cobieUnits == "millimeters" || cobieUnits == "millimetres")
            {
                conversionFactor = Model.ModelFactors.OneMilliMetre;
            }
            else if (cobieUnits == "feet" || cobieUnits == "foot")
            {
                conversionFactor = Model.ModelFactors.OneFoot;
            }
            else if (cobieUnits == "inch" || cobieUnits == "inches")
            {
                conversionFactor = Model.ModelFactors.OneInch;
            }
            else
            {
                throw new Exception(
                          string.Format("The COBie units are incorrectly set, the provided value {0} is invalid.",
                                        cobieUnits));
            }

            XbimMatrix3D globalTransform = XbimMatrix3D.CreateScale(1 / conversionFactor);

            var coordinates = new COBieSheet <COBieCoordinateRow>(Constants.WORKSHEET_COORDINATE);

            ProgressIndicator.ReportMessage("Starting Coordinates...");


            //Create new sheet

            //Get buildings and spaces
            var ifcBuildingStoreys = Model.FederatedInstances.OfType <IfcBuildingStorey>();
            var ifcSpaces          = Model.FederatedInstances.OfType <IfcSpace>()
                                     .OrderBy(ifcSpace => ifcSpace.Name, new CompareIfcLabel());
            var ifcProducts = ifcBuildingStoreys.Union <IfcProduct>(ifcSpaces); //add spaces

            //get component products as shown in Component sheet
            var relAggregates = Model.FederatedInstances.OfType <IfcRelAggregates>();
            var relSpatial    = Model.FederatedInstances.OfType <IfcRelContainedInSpatialStructure>();
            var ifcElements   = ((from x in relAggregates
                                  from y in x.RelatedObjects
                                  where !Context.Exclude.ObjectType.Component.Contains(y.GetType())
                                  select y).Union(from x in relSpatial
                                                  from y in x.RelatedElements
                                                  where !Context.Exclude.ObjectType.Component.Contains(y.GetType())
                                                  select y)).OfType <IfcProduct>(); //.GroupBy(el => el.Name).Select(g => g.First())

            ifcProducts = ifcProducts.Union(ifcElements);

            var productList = ifcProducts as IList <IfcProduct> ?? ifcProducts.ToList();

            ProgressIndicator.Initialise("Creating Coordinates", productList.Count());

            var m3D = new Xbim3DModelContext(Model);

            foreach (var ifcProduct in productList)
            {
                ProgressIndicator.IncrementAndUpdate();
                //if no name to link the row name too skip it, as no way to link back to the parent object
                //if (string.IsNullOrEmpty(ifcProduct.Name))
                //    continue;

                var coordinate = new COBieCoordinateRow(coordinates)
                {
                    Name = (string.IsNullOrEmpty(ifcProduct.Name.ToString()))
                        ? DEFAULT_STRING
                        : ifcProduct.Name.ToString(),
                    CreatedBy = GetTelecomEmailAddress(ifcProduct.OwnerHistory),
                    CreatedOn = GetCreatedOnDateAsFmtString(ifcProduct.OwnerHistory)
                };

                // (ifcBuildingStorey == null || ifcBuildingStorey.Name.ToString() == "") ? "CoordinateName" : ifcBuildingStorey.Name.ToString();

                coordinate.RowName = coordinate.Name;

                XbimPoint3D?ifcCartesianPointLower = null;
                XbimPoint3D?ifcCartesianPointUpper = null;
                var         transBox = new TransformedBoundingBox();
                if (ifcProduct is IfcBuildingStorey)
                {
                    XbimMatrix3D worldMatrix = ifcProduct.ObjectPlacement.ToMatrix3D();
                    ifcCartesianPointLower = new XbimPoint3D(worldMatrix.OffsetX, worldMatrix.OffsetY,
                                                             worldMatrix.OffsetZ);
                    //get the offset from the world coordinates system 0,0,0 point, i.e. origin point of this object in world space
                    coordinate.SheetName   = "Floor";
                    coordinate.Category    = "point";
                    ifcCartesianPointUpper = null;
                }
                else
                {
                    if (ifcProduct is IfcSpace)
                    {
                        coordinate.SheetName = "Space";
                    }
                    else
                    {
                        coordinate.SheetName = "Component";
                    }

                    coordinate.Category = "box-lowerleft"; //and box-upperright, so two values required when we do this

                    var          boundBox  = XbimRect3D.Empty;
                    XbimMatrix3D transform = XbimMatrix3D.Identity;
                    foreach (var shapeInstance in m3D.ShapeInstancesOf(ifcProduct))
                    {
                        if (boundBox.IsEmpty)
                        {
                            boundBox = shapeInstance.BoundingBox;
                        }
                        else
                        {
                            boundBox.Union(shapeInstance.BoundingBox);
                        }
                        transform = shapeInstance.Transformation;
                    }
                    if (!boundBox.IsEmpty)
                    {
                        XbimMatrix3D m = globalTransform * transform;
                        transBox = new TransformedBoundingBox(boundBox, m);
                        //set points
                        ifcCartesianPointLower = transBox.MinPt;
                        ifcCartesianPointUpper = transBox.MaxPt;
                    }
                }

                if (ifcCartesianPointLower.HasValue)
                {
                    coordinate.CoordinateXAxis = string.Format("{0}", (double)ifcCartesianPointLower.Value.X);
                    coordinate.CoordinateYAxis = string.Format("{0}", (double)ifcCartesianPointLower.Value.Y);
                    coordinate.CoordinateZAxis = string.Format("{0}", (double)ifcCartesianPointLower.Value.Z);
                    coordinate.ExtSystem       = GetExternalSystem(ifcProduct);
                    coordinate.ExtObject       = ifcProduct.GetType().Name;
                    if (!string.IsNullOrEmpty(ifcProduct.GlobalId))
                    {
                        coordinate.ExtIdentifier = ifcProduct.GlobalId.ToString();
                    }

                    coordinate.ClockwiseRotation   = transBox.ClockwiseRotation.ToString("F4");
                    coordinate.ElevationalRotation = transBox.ElevationalRotation.ToString("F4");
                    coordinate.YawRotation         = transBox.YawRotation.ToString("F4");

                    coordinates.AddRow(coordinate);
                }

                if (ifcCartesianPointUpper.HasValue) //we need a second row for upper point
                {
                    var coordinateUpper = new COBieCoordinateRow(coordinates);
                    coordinateUpper.Name                = coordinate.Name;
                    coordinateUpper.CreatedBy           = coordinate.CreatedBy;
                    coordinateUpper.CreatedOn           = coordinate.CreatedOn;
                    coordinateUpper.RowName             = coordinate.RowName;
                    coordinateUpper.SheetName           = coordinate.SheetName;
                    coordinateUpper.Category            = "box-upperright";
                    coordinateUpper.CoordinateXAxis     = string.Format("{0}", (double)ifcCartesianPointUpper.Value.X);
                    coordinateUpper.CoordinateYAxis     = string.Format("{0}", (double)ifcCartesianPointUpper.Value.Y);
                    coordinateUpper.CoordinateZAxis     = string.Format("{0}", (double)ifcCartesianPointUpper.Value.Z);
                    coordinateUpper.ExtSystem           = coordinate.ExtSystem;
                    coordinateUpper.ExtObject           = coordinate.ExtObject;
                    coordinateUpper.ExtIdentifier       = coordinate.ExtIdentifier;
                    coordinateUpper.ClockwiseRotation   = coordinate.ClockwiseRotation;
                    coordinateUpper.ElevationalRotation = coordinate.ElevationalRotation;
                    coordinateUpper.YawRotation         = coordinate.YawRotation;

                    coordinates.AddRow(coordinateUpper);
                }
            }

            coordinates.OrderBy(s => s.Name);

            ProgressIndicator.Finalise();


            return(coordinates);
        }
        /// <summary>
        /// Fill sheet rows for Connection sheet
        /// </summary>
        /// <returns>COBieSheet</returns>
        public override COBieSheet <COBieConnectionRow> Fill()
        {
            ProgressIndicator.ReportMessage("Starting Connections...");
            //Create new sheet
            COBieSheet <COBieConnectionRow> connections = new COBieSheet <COBieConnectionRow>(Constants.WORKSHEET_CONNECTION);

            // get all IfcRelConnectsElements objects from IFC file
            IEnumerable <IfcRelConnectsElements> ifcRelConnectsElements = Model.Instances.OfType <IfcRelConnectsElements>()
                                                                          .Where(rce => rce.RelatedElement != null &&
                                                                                 !Context.Exclude.ObjectType.Component.Contains(rce.RelatedElement.GetType()) &&
                                                                                 rce.RelatingElement != null &&
                                                                                 !Context.Exclude.ObjectType.Component.Contains(rce.RelatingElement.GetType())
                                                                                 );
            //get ifcRelConnectsPorts only if we have ifcRelConnectsElements
            IEnumerable <IfcRelConnectsPorts> ifcRelConnectsPorts = Enumerable.Empty <IfcRelConnectsPorts>();

            if (ifcRelConnectsElements.Count() > 0)
            {
                ifcRelConnectsPorts = Model.Instances.OfType <IfcRelConnectsPorts>();
            }

            ProgressIndicator.Initialise("Creating Connections", ifcRelConnectsElements.Count());

            int ids = 0;

            foreach (IfcRelConnectsElements ifcRelConnectsElement in ifcRelConnectsElements)
            {
                ProgressIndicator.IncrementAndUpdate();

                IfcElement relatingElement = ifcRelConnectsElement.RelatingElement;
                IfcElement relatedElement  = ifcRelConnectsElement.RelatedElement;

                COBieConnectionRow conn = new COBieConnectionRow(connections);

                //try and get the IfcRelConnectsPorts first for relatingElement then for relatedElement
                IEnumerable <IfcRelConnectsPorts> ifcRelConnectsPortsElement = ifcRelConnectsPorts.Where(rcp => (rcp.RealizingElement != null) && ((rcp.RealizingElement == relatingElement) || (rcp.RealizingElement == relatedElement)));
                string connectionName = "";
                connectionName = (string.IsNullOrEmpty(ifcRelConnectsElement.Name)) ? "" : ifcRelConnectsElement.Name.ToString();


                conn.CreatedBy      = GetTelecomEmailAddress(ifcRelConnectsElement.OwnerHistory);
                conn.CreatedOn      = GetCreatedOnDateAsFmtString(ifcRelConnectsElement.OwnerHistory);
                conn.ConnectionType = GetComponentDescription(ifcRelConnectsElement);
                conn.SheetName      = GetSheetByObjectType(relatingElement.GetType());

                conn.RowName1 = ((relatingElement != null) && (!string.IsNullOrEmpty(relatingElement.Name.ToString()))) ? relatingElement.Name.ToString() : DEFAULT_STRING;
                conn.RowName2 = ((relatedElement != null) && (!string.IsNullOrEmpty(relatedElement.Name.ToString()))) ? relatedElement.Name.ToString() : DEFAULT_STRING;
                //second attempt to get a name, if no IfcElement name then see if the associated type has a name
                //if (conn.RowName1 == DEFAULT_STRING) conn.RowName1 =  GetTypeName(relatingElement);
                //if (conn.RowName2 == DEFAULT_STRING) conn.RowName2 = GetTypeName(relatedElement);

                //try and get IfcRelConnectsPorts by using relatingElement then relatedElement is the RelizingElement, but this is optional property, but the IfcRelConnectsPorts object document states
                //"Each of the port is being attached to the IfcElement by using the IfcRelConnectsPortToElement relationship" and the IfcRelConnectsPortToElement is a inverse reference to HasPorts
                //on the IfcElement, so if no IfcRelConnectsPorts found for either Element, then check the HasPosts property of each element.
                List <string> realizingElement = new List <string>();
                List <string> relatedPort      = new List <string>();
                List <string> relatingPort     = new List <string>();
                foreach (IfcRelConnectsPorts port  in ifcRelConnectsPortsElement)
                {
                    if ((string.IsNullOrEmpty(connectionName)) && (string.IsNullOrEmpty(port.Name)))
                    {
                        connectionName = port.Name;
                    }

                    if ((port.RealizingElement != null) && (!string.IsNullOrEmpty(port.RealizingElement.ToString())))  //removed to allow export to xbim to keep sequence && (!realizingElement.Contains(port.RealizingElement.ToString()))
                    {
                        realizingElement.Add(port.RealizingElement.ToString());
                    }

                    if ((port.RelatedPort != null) && (!string.IsNullOrEmpty(port.RelatedPort.Name.ToString()))) //removed to allow export to xbim to keep sequence && (!relatedPort.Contains(port.RelatedPort.Name.ToString()))
                    {
                        relatedPort.Add(port.RelatedPort.Name.ToString());
                    }

                    if ((port.RelatingPort != null) && (!string.IsNullOrEmpty(port.RelatingPort.Name.ToString()))) //removed to allow export to xbim to keep sequence && (!relatingPort.Contains(port.RelatingPort.Name.ToString()))
                    {
                        relatingPort.Add(port.RelatingPort.Name.ToString());
                    }
                }

                conn.RealizingElement = (realizingElement.Count > 0) ? COBieXBim.JoinStrings(':', realizingElement) : DEFAULT_STRING;

                //no related port found so lets try and get from IfcElement.HasPorts
                if (relatedPort.Count == 0)
                {
                    IEnumerable <IfcRelConnectsPortToElement> relatedPorts = relatedElement.HasPorts.Where(rcpe => rcpe.RelatingPort != null);
                    foreach (IfcRelConnectsPortToElement port in relatedPorts)
                    {
                        if ((string.IsNullOrEmpty(connectionName)) && (string.IsNullOrEmpty(port.Name)))
                        {
                            connectionName = port.Name;
                        }
                        if ((port.RelatingPort != null) && (!string.IsNullOrEmpty(port.RelatingPort.Name.ToString())) && (!relatedPort.Contains(port.RelatingPort.Name.ToString())))
                        {
                            relatedPort.Add(port.RelatingPort.Name.ToString());
                        }
                    }
                }
                //no relating port found so lets try and get from IfcElement.HasPorts
                if (relatingPort.Count == 0)
                {
                    IEnumerable <IfcRelConnectsPortToElement> relatingPorts = relatingElement.HasPorts.Where(rcpe => rcpe.RelatingPort != null);
                    foreach (IfcRelConnectsPortToElement port in relatingPorts)
                    {
                        if ((string.IsNullOrEmpty(connectionName)) && (string.IsNullOrEmpty(port.Name)))
                        {
                            connectionName = port.Name;
                        }
                        if ((port.RelatingPort != null) && (!string.IsNullOrEmpty(port.RelatingPort.Name.ToString())) && (!relatedPort.Contains(port.RelatingPort.Name.ToString())))
                        {
                            relatingPort.Add(port.RelatingPort.Name.ToString());
                        }
                    }
                }

                conn.PortName1 = (relatingPort.Count > 0) ? COBieXBim.JoinStrings(':', relatingPort) : DEFAULT_STRING;
                conn.PortName2 = (relatedPort.Count > 0) ? COBieXBim.JoinStrings(':', relatedPort) : DEFAULT_STRING;

                conn.ExtSystem     = GetExternalSystem(ifcRelConnectsElement);
                conn.ExtObject     = ifcRelConnectsElement.GetType().Name;
                conn.ExtIdentifier = ifcRelConnectsElement.GlobalId;

                //if no ifcRelConnectsElement Name or Port names then revert to the index number
                conn.Name        = (string.IsNullOrEmpty(connectionName)) ? ids.ToString() : connectionName;
                conn.Description = (string.IsNullOrEmpty(ifcRelConnectsElement.Description)) ? DEFAULT_STRING : ifcRelConnectsElement.Description.ToString();

                connections.AddRow(conn);

                ids++;
            }

            connections.OrderBy(s => s.Name);

            ProgressIndicator.Finalise();

            return(connections);
        }
        /// <summary>
        /// Unregister entities and cascade the operation
        /// </summary>
        /// <param name="org">Organization to be used</param>
        /// <param name="crmEntity">Entities to be unregistered. If these are not invalid entities, only one can be specified</param>
        /// <param name="cascadeOperation">Cascade the operation</param>
        /// <param name="prog">ProgressIndicator to indicate success</param>
        /// <returns>Statistics of what was unregistered</returns>
        public static Dictionary <string, int> Unregister(CrmOrganization org, ProgressIndicator prog, params ICrmEntity[] crmEntity)
        {
            if (org == null)
            {
                throw new ArgumentNullException("org");
            }
            else if (crmEntity == null || crmEntity.Length == 0)
            {
                throw new ArgumentNullException("crmEntity");
            }

            Collection <Guid> serviceEndpointList = new Collection <Guid>();
            Collection <Guid> assemblyList        = new Collection <Guid>();
            Collection <Guid> pluginList          = new Collection <Guid>();
            Collection <Guid> stepList            = new Collection <Guid>();
            Collection <Guid> secureConfigList    = new Collection <Guid>();
            Collection <Guid> imageList           = new Collection <Guid>();

            //Create the list of various objects that need to be unregistered
            foreach (ICrmEntity entity in crmEntity)
            {
                switch (entity.EntityType)
                {
                case ServiceEndpoint.EntityLogicalName:
                    serviceEndpointList.Add(entity.EntityId);
                    break;

                case PluginAssembly.EntityLogicalName:
                    assemblyList.Add(entity.EntityId);
                    break;

                case PluginType.EntityLogicalName:
                    pluginList.Add(entity.EntityId);
                    break;

                case Entities.SdkMessageProcessingStep.EntityLogicalName:
                    stepList.Add(entity.EntityId);
                    break;

                case SdkMessageProcessingStepImage.EntityLogicalName:
                    imageList.Add(entity.EntityId);
                    break;

                default:
                    throw new NotImplementedException("Type = " + entity.EntityType.ToString());
                }
            }

            //Retrieve the up-to-date list of steps for the service endpoints and add them to the unregister list
            foreach (Guid stepId in RetrieveStepIdsForServiceEndpoint(org, serviceEndpointList))
            {
                if (!stepList.Contains(stepId))
                {
                    stepList.Add(stepId);
                }
            }
            //Retrieve the up-to-date list of plugins for the assemblies and add them to the unregister list
            foreach (Guid pluginId in RetrievePluginIdsForAssembly(org, assemblyList))
            {
                if (!pluginList.Contains(pluginId))
                {
                    pluginList.Add(pluginId);
                }
            }

            //Retrieve the up-to-date list of steps for the plugins and add them to the unregister list
            foreach (Guid stepId in RetrieveStepIdsForPlugins(org, pluginList))
            {
                if (!stepList.Contains(stepId))
                {
                    stepList.Add(stepId);
                }
            }

            //Retrieve all of the profiler steps that need to be deleted
            for (int i = stepList.Count - 1; i >= 0; i--)
            {
                CrmPluginStep step;
                if (org.Steps.TryGetValue(stepList[i], out step))
                {
                    Guid profilerStepId = step.ProfilerStepId.GetValueOrDefault();
                    if (Guid.Empty != profilerStepId && profilerStepId != step.StepId)
                    {
                        stepList.Add(profilerStepId);
                    }
                }
            }

            //Retrieve the up-to-date list of secure configs for the steps and add them to the unregister list
            foreach (Guid secureConfigId in RetrieveSecureConfigIdsForStepId(org, stepList))
            {
                if (!secureConfigList.Contains(secureConfigId))
                {
                    secureConfigList.Add(secureConfigId);
                }
            }

            //Retrieve the up-to-date list of images for the steps and add them to the unregister list
            foreach (Guid imageId in RetrieveImageIdsForStepId(org, stepList))
            {
                if (!imageList.Contains(imageId))
                {
                    imageList.Add(imageId);
                }
            }

            //Loop through each object and delete them
            Dictionary <string, int> deleteStats = new Dictionary <string, int>();
            int totalSteps = secureConfigList.Count + 1;

            if (serviceEndpointList.Count != 0)
            {
                deleteStats.Add(serviceEndpointList.Count == 1 ? "ServiceEndpoint" : "ServiceEndpoints", serviceEndpointList.Count);
                totalSteps += serviceEndpointList.Count;
            }
            if (assemblyList.Count != 0)
            {
                deleteStats.Add(assemblyList.Count == 1 ? "Assembly" : "Assemblies", assemblyList.Count);
                totalSteps += assemblyList.Count;
            }
            if (pluginList.Count != 0)
            {
                deleteStats.Add(pluginList.Count == 1 ? "Plugin" : "Plugins", pluginList.Count);
                totalSteps += pluginList.Count;
            }
            if (stepList.Count != 0)
            {
                deleteStats.Add(stepList.Count == 1 ? "Step" : "Steps", stepList.Count);
                totalSteps += stepList.Count;
            }
            if (imageList.Count != 0)
            {
                deleteStats.Add(imageList.Count == 1 ? "Image" : "Images", imageList.Count);
                totalSteps += imageList.Count;
            }

            try
            {
                if (prog != null)
                {
                    prog.Initialize(totalSteps, "Unregistering Images");
                }
                foreach (Guid imageId in imageList)
                {
                    org.OrganizationService.Delete(SdkMessageProcessingStepImage.EntityLogicalName, imageId);
                    if (prog != null)
                    {
                        prog.Increment();
                    }
                }

                if (prog != null)
                {
                    prog.SetText("Unregistering Steps");
                }
                foreach (Guid stepId in stepList)
                {
                    org.OrganizationService.Delete(SdkMessageProcessingStep.EntityLogicalName, stepId);
                    if (prog != null)
                    {
                        prog.Increment();
                    }
                }

                if (prog != null)
                {
                    prog.SetText("Unregistering Secure Configuration");
                }
                foreach (Guid secureConfigId in secureConfigList)
                {
                    org.OrganizationService.Delete(SdkMessageProcessingStepSecureConfig.EntityLogicalName, secureConfigId);
                    if (prog != null)
                    {
                        prog.Increment();
                    }
                }

                if (prog != null)
                {
                    prog.SetText("Unregistering Plugins");
                }
                foreach (Guid pluginId in pluginList)
                {
                    org.OrganizationService.Delete(PluginType.EntityLogicalName, pluginId);
                    if (prog != null)
                    {
                        prog.Increment();
                    }
                }

                if (prog != null)
                {
                    prog.SetText("Unregistering Assemblies");
                }
                foreach (Guid assemblyId in assemblyList)
                {
                    org.OrganizationService.Delete(PluginAssembly.EntityLogicalName, assemblyId);
                    if (prog != null)
                    {
                        prog.Increment();
                    }
                }

                if (prog != null)
                {
                    prog.SetText("Unregistering ServiceEndpoints");
                }
                foreach (Guid serviceEndpointId in serviceEndpointList)
                {
                    org.OrganizationService.Delete(ServiceEndpoint.EntityLogicalName, serviceEndpointId);
                    if (prog != null)
                    {
                        prog.Increment();
                    }
                }
            }
            finally
            {
                if (prog != null)
                {
                    prog.Complete(true);
                }
            }

            return(deleteStats);
        }
Example #48
0
 public void Initialize(PhoneApplicationFrame frame)
 {
     _mangoIndicator   = new ProgressIndicator();
     frame.Navigating += new NavigatingCancelEventHandler(frame_Navigating);
     frame.Navigated  += OnRootFrameNavigated;
 }
Example #49
0
        /// <summary>
        /// Fill sheet rows for Floor sheet
        /// </summary>
        /// <returns>COBieSheet</returns>
        public override COBieSheet <COBieFloorRow> Fill()
        {
            ProgressIndicator.ReportMessage("Starting Floors...");

            //create new sheet
            COBieSheet <COBieFloorRow> floors = new COBieSheet <COBieFloorRow>(Constants.WORKSHEET_FLOOR);

            // get all IfcBuildingStory objects from IFC file
            IEnumerable <IfcBuildingStorey> buildingStories = Model.Instances.OfType <IfcBuildingStorey>();

            COBieDataPropertySetValues allPropertyValues = new COBieDataPropertySetValues(); //properties helper class
            COBieDataAttributeBuilder  attributeBuilder  = new COBieDataAttributeBuilder(Context, allPropertyValues);

            attributeBuilder.InitialiseAttributes(ref _attributes);


            //IfcClassification ifcClassification = Model.Instances.OfType<IfcClassification>().FirstOrDefault();
            //list of attributes to exclude form attribute sheet

            //set up filters on COBieDataPropertySetValues for the SetAttributes only
            attributeBuilder.ExcludeAttributePropertyNames.AddRange(Context.Exclude.Floor.AttributesEqualTo);
            attributeBuilder.ExcludeAttributePropertyNamesWildcard.AddRange(Context.Exclude.Floor.AttributesContain);
            attributeBuilder.RowParameters["Sheet"] = "Floor";



            ProgressIndicator.Initialise("Creating Floors", buildingStories.Count());

            foreach (IfcBuildingStorey ifcBuildingStorey in buildingStories)
            {
                ProgressIndicator.IncrementAndUpdate();

                COBieFloorRow floor = new COBieFloorRow(floors);
                string        name  = ifcBuildingStorey.Name;
                if (string.IsNullOrEmpty(ifcBuildingStorey.Name))
                {
                    ifcBuildingStorey.Name = "Name Unknown " + UnknownCount.ToString();
                    UnknownCount++;
                }

                //set allPropertyValues to this element
                allPropertyValues.SetAllPropertyValues(ifcBuildingStorey); //set the internal filtered IfcPropertySingleValues List in allPropertyValues


                floor.Name = name;

                string createBy = allPropertyValues.GetPropertySingleValueValue("COBieCreatedBy", false);  //support for COBie Toolkit for Autodesk Revit
                floor.CreatedBy = ValidateString(createBy) ? createBy : GetTelecomEmailAddress(ifcBuildingStorey.OwnerHistory);
                string createdOn = allPropertyValues.GetPropertySingleValueValue("COBieCreatedOn", false); //support for COBie Toolkit for Autodesk Revit
                floor.CreatedOn = ValidateString(createdOn) ? createdOn : GetCreatedOnDateAsFmtString(ifcBuildingStorey.OwnerHistory);

                floor.Category = GetCategory(ifcBuildingStorey);

                string extSystem = allPropertyValues.GetPropertySingleValueValue("COBieExtSystem", false);//support for COBie Toolkit for Autodesk Revit
                floor.ExtSystem     = ValidateString(extSystem) ? extSystem : GetExternalSystem(ifcBuildingStorey);
                floor.ExtObject     = ifcBuildingStorey.GetType().Name;
                floor.ExtIdentifier = ifcBuildingStorey.GlobalId;
                string description = allPropertyValues.GetPropertySingleValueValue("COBieDescription", false);//support for COBie Toolkit for Autodesk Revit
                floor.Description = ValidateString(description) ? description : GetFloorDescription(ifcBuildingStorey);
                floor.Elevation   = (string.IsNullOrEmpty(ifcBuildingStorey.Elevation.ToString())) ? DEFAULT_NUMERIC : string.Format("{0}", (double)ifcBuildingStorey.Elevation);

                floor.Height = GetFloorHeight(ifcBuildingStorey, allPropertyValues);

                floors.AddRow(floor);

                //fill in the attribute information
                attributeBuilder.RowParameters["Name"]      = floor.Name;
                attributeBuilder.RowParameters["CreatedBy"] = floor.CreatedBy;
                attributeBuilder.RowParameters["CreatedOn"] = floor.CreatedOn;
                attributeBuilder.RowParameters["ExtSystem"] = floor.ExtSystem;
                attributeBuilder.PopulateAttributesRows(ifcBuildingStorey); //fill attribute sheet rows//pass data from this sheet info as Dictionary
            }

            floors.OrderBy(s => s.Name);

            ProgressIndicator.Finalise();

            return(floors);
        }
 public ProgressService(ProgressIndicator progressIndicator)
 {
     m_progressIndicator = progressIndicator;
 }
Example #51
0
        /// <summary>
        /// Fill sheet rows for Job sheet
        /// </summary>
        /// <returns>COBieSheet</returns>
        public override COBieSheet <COBieJobRow> Fill()
        {
            ProgressIndicator.ReportMessage("Starting Jobs...");

            //create new sheet
            var jobs = new COBieSheet <COBieJobRow>(Constants.WORKSHEET_JOB);

            // get all IfcTask objects from IFC file
            var ifcTasks = Model.FederatedInstances.OfType <IfcTask>();

            var allPropertyValues = new COBieDataPropertySetValues(); //properties helper class

            //IfcTypeObject typObj = Model.FederatedInstances.OfType<IfcTypeObject>().FirstOrDefault();
            var cer = Model.FederatedInstances.OfType <IfcConstructionEquipmentResource>().FirstOrDefault();

            ProgressIndicator.Initialise("Creating Jobs", ifcTasks.Count());

            foreach (var ifcTask in ifcTasks)
            {
                ProgressIndicator.IncrementAndUpdate();

                if (ifcTask == null)
                {
                    continue;
                }

                var job = new COBieJobRow(jobs);

                job.Name      = (string.IsNullOrEmpty(ifcTask.Name.ToString())) ? DEFAULT_STRING : ifcTask.Name.ToString();
                job.CreatedBy = GetTelecomEmailAddress(ifcTask.OwnerHistory);
                job.CreatedOn = GetCreatedOnDateAsFmtString(ifcTask.OwnerHistory);
                job.Category  = ifcTask.ObjectType.ToString();
                job.Status    = (string.IsNullOrEmpty(ifcTask.Status.ToString())) ? DEFAULT_STRING : ifcTask.Status.ToString();

                job.TypeName    = GetObjectType(ifcTask);
                job.Description = (string.IsNullOrEmpty(ifcTask.Description.ToString())) ? DEFAULT_STRING : ifcTask.Description.ToString();

                allPropertyValues.SetAllPropertyValues(ifcTask); //set properties values to this task
                var ifcPropertySingleValue = allPropertyValues.GetPropertySingleValue("TaskDuration");
                job.Duration = ((ifcPropertySingleValue != null) && (ifcPropertySingleValue.NominalValue != null)) ? ConvertNumberOrDefault(ifcPropertySingleValue.NominalValue.ToString()) : DEFAULT_NUMERIC;
                var unitName = ((ifcPropertySingleValue != null) && (ifcPropertySingleValue.Unit != null)) ? GetUnitName(ifcPropertySingleValue.Unit) : null;
                job.DurationUnit = (string.IsNullOrEmpty(unitName)) ?  DEFAULT_STRING : unitName;

                ifcPropertySingleValue = allPropertyValues.GetPropertySingleValue("TaskStartDate");
                job.Start         = GetStartTime(ifcPropertySingleValue);
                unitName          = ((ifcPropertySingleValue != null) && (ifcPropertySingleValue.Unit != null)) ? GetUnitName(ifcPropertySingleValue.Unit) : null;
                job.TaskStartUnit = (string.IsNullOrEmpty(unitName)) ? DEFAULT_STRING : unitName;

                ifcPropertySingleValue = allPropertyValues.GetPropertySingleValue("TaskInterval");
                job.Frequency          = ((ifcPropertySingleValue != null) && (ifcPropertySingleValue.NominalValue != null)) ? ConvertNumberOrDefault(ifcPropertySingleValue.NominalValue.ToString()) : DEFAULT_NUMERIC;
                unitName          = ((ifcPropertySingleValue != null) && (ifcPropertySingleValue.Unit != null)) ? GetUnitName(ifcPropertySingleValue.Unit) : null;
                job.FrequencyUnit = (string.IsNullOrEmpty(unitName)) ? DEFAULT_STRING : unitName;

                job.ExtSystem     = GetExternalSystem(ifcTask);
                job.ExtObject     = ifcTask.GetType().Name;
                job.ExtIdentifier = ifcTask.GlobalId;

                job.TaskNumber    = (string.IsNullOrEmpty(ifcTask.TaskId.ToString())) ? DEFAULT_STRING : ifcTask.TaskId.ToString();
                job.Priors        = GetPriors(ifcTask);
                job.ResourceNames = GetResources(ifcTask);

                jobs.AddRow(job);
            }

            jobs.OrderBy(s => s.Name);

            ProgressIndicator.Finalise();
            return(jobs);
        }
Example #52
0
 public static void SetProgressIndicator(WpfApplicationPage page, ProgressIndicator progressIndicator)
 {
     // todo
     //throw new NotImplementedException();
 }
Example #53
0
        /// <summary>
        /// Fill sheet rows for Zone sheet
        /// </summary>
        /// <returns>COBieSheet</returns>
        public override COBieSheet <COBieZoneRow> Fill()
        {
            ProgressIndicator.ReportMessage("Starting Zones...");

            //Create new sheet
            COBieSheet <COBieZoneRow> zones = new COBieSheet <COBieZoneRow>(Constants.WORKSHEET_ZONE);


            // get all IfcBuildingStory objects from IFC file
            IEnumerable <IfcZone> ifcZones = Model.FederatedInstances.OfType <IfcZone>();

            COBieDataPropertySetValues allPropertyValues = new COBieDataPropertySetValues(); //properties helper class
            COBieDataAttributeBuilder  attributeBuilder  = new COBieDataAttributeBuilder(Context, allPropertyValues);

            attributeBuilder.InitialiseAttributes(ref _attributes);

            //list of attributes to exclude form attribute sheet
            attributeBuilder.ExcludeAttributePropertyNamesWildcard.AddRange(Context.Exclude.Zone.AttributesContain);
            attributeBuilder.RowParameters["Sheet"] = "Zone";

            //Also check to see if we have any zones within the spaces
            IEnumerable <IfcSpace> ifcSpaces = Model.FederatedInstances.OfType <IfcSpace>();//.OrderBy(ifcSpace => ifcSpace.Name, new CompareIfcLabel());

            ProgressIndicator.Initialise("Creating Zones", ifcZones.Count() + ifcSpaces.Count());

            foreach (IfcZone zn in ifcZones)
            {
                ProgressIndicator.IncrementAndUpdate();
                // create zone for each space found
                Dictionary <String, COBieZoneRow> ExistingZones = new Dictionary <string, COBieZoneRow>();
                IEnumerable <IfcSpace>            spaces        = (zn.IsGroupedBy == null) ? Enumerable.Empty <IfcSpace>() : zn.IsGroupedBy.RelatedObjects.OfType <IfcSpace>();
                foreach (IfcSpace sp in spaces)
                {
                    COBieZoneRow zone;
                    if (ExistingZones.ContainsKey(zn.Name.ToString()))
                    {
                        zone             = ExistingZones[zn.Name.ToString()];
                        zone.SpaceNames += "," + sp.Name.ToString();
                    }
                    else
                    {
                        zone = new COBieZoneRow(zones);
                        ExistingZones[zn.Name.ToString()] = zone;

                        //set allPropertyValues to this element
                        allPropertyValues.SetAllPropertyValues(zn); //set the internal filtered IfcPropertySingleValues List in allPropertyValues

                        zone.Name = zn.Name.ToString();

                        string createBy = allPropertyValues.GetPropertySingleValueValue("COBieCreatedBy", false);  //support for COBie Toolkit for Autodesk Revit
                        zone.CreatedBy = ValidateString(createBy) ? createBy : GetTelecomEmailAddress(zn.OwnerHistory);
                        string createdOn = allPropertyValues.GetPropertySingleValueValue("COBieCreatedOn", false); //support for COBie Toolkit for Autodesk Revit
                        zone.CreatedOn = ValidateString(createdOn) ? createdOn : GetCreatedOnDateAsFmtString(zn.OwnerHistory);

                        zone.Category = GetCategory(zn);

                        zone.SpaceNames = sp.Name;

                        string extSystem = allPropertyValues.GetPropertySingleValueValue("COBieExtSystem", false);//support for COBie Toolkit for Autodesk Revit
                        zone.ExtSystem     = ValidateString(extSystem) ? extSystem : GetExternalSystem(zn);
                        zone.ExtObject     = zn.GetType().Name;
                        zone.ExtIdentifier = zn.GlobalId;
                        string description = allPropertyValues.GetPropertySingleValueValue("COBieDescription", false);//support for COBie Toolkit for Autodesk Revit
                        if (ValidateString(extSystem))
                        {
                            zone.Description = extSystem;
                        }
                        else
                        {
                            zone.Description = (string.IsNullOrEmpty(zn.Description)) ? zn.Name.ToString() : zn.Description.ToString(); //if IsNullOrEmpty on Description then output Name
                        }
                        zones.AddRow(zone);

                        //fill in the attribute information
                        attributeBuilder.RowParameters["Name"]      = zone.Name;
                        attributeBuilder.RowParameters["CreatedBy"] = zone.CreatedBy;
                        attributeBuilder.RowParameters["CreatedOn"] = zone.CreatedOn;
                        attributeBuilder.RowParameters["ExtSystem"] = zone.ExtSystem;
                        attributeBuilder.PopulateAttributesRows(zn); //fill attribute sheet rows//pass data from this sheet info as Dictionary
                    }
                }
            }

            COBieDataPropertySetValues allSpacePropertyValues = new COBieDataPropertySetValues(); //get all property sets and associated properties in one go

            Dictionary <String, COBieZoneRow> myExistingZones = new Dictionary <string, COBieZoneRow>();

            foreach (IfcSpace sp in ifcSpaces)
            {
                ProgressIndicator.IncrementAndUpdate();
                allSpacePropertyValues.SetAllPropertyValues(sp); //set the space as the current object for the properties get glass

                IEnumerable <IfcPropertySingleValue> spProperties = Enumerable.Empty <IfcPropertySingleValue>();
                foreach (KeyValuePair <IfcPropertySet, IEnumerable <IfcSimpleProperty> > item in allSpacePropertyValues.MapPsetToProps)
                {
                    IfcPropertySet pset = item.Key;
                    spProperties = item.Value.Where(p => p.Name.ToString().Contains("ZoneName")).OfType <IfcPropertySingleValue>();


                    //if we have no ifcZones or "ZoneName" properties, and the DepartmentsUsedAsZones flag is true then list departments as zones
                    if ((!spProperties.Any()) && (!ifcZones.Any()) && (Context.DepartmentsUsedAsZones == true))
                    {
                        spProperties = item.Value.Where(p => p.Name == "Department").OfType <IfcPropertySingleValue>();
                    }

                    foreach (IfcPropertySingleValue spProp in spProperties)
                    {
                        COBieZoneRow zone;
                        if (myExistingZones.ContainsKey(spProp.NominalValue.ToString()))
                        {
                            zone             = myExistingZones[spProp.NominalValue.ToString()];
                            zone.SpaceNames += "," + sp.Name;
                        }
                        else
                        {
                            zone      = new COBieZoneRow(zones);
                            zone.Name = spProp.NominalValue.ToString();
                            myExistingZones[spProp.NominalValue.ToString()] = zone;

                            zone.CreatedBy = GetTelecomEmailAddress(sp.OwnerHistory);
                            zone.CreatedOn = GetCreatedOnDateAsFmtString(sp.OwnerHistory);

                            zone.Category   = spProp.Name;
                            zone.SpaceNames = sp.Name;

                            zone.ExtSystem     = GetExternalSystem(pset);
                            zone.ExtObject     = spProp.GetType().Name;
                            zone.ExtIdentifier = pset.GlobalId.ToString(); //IfcPropertySingleValue has no GlobalId so set to the holding IfcPropertySet

                            zone.Description = (string.IsNullOrEmpty(spProp.NominalValue.ToString())) ? DEFAULT_STRING : spProp.NominalValue.ToString();;

                            zones.AddRow(zone);
                        }
                    }
                }
                //spProperties = spProperties.OrderBy(p => p.Name.ToString(), new CompareString()); //consolidate test, Concat as looping spaces then sort then dump to COBieZoneRow foreach
            }

            zones.OrderBy(s => s.Name);

            ProgressIndicator.Finalise();

            return(zones);
        }
Example #54
0
        // Constructor
        public MainPage()
        {
            InitializeComponent();


            #region trial Check
            if (App.IsTrial == true)
            {
                // enable ads
                adControl.Visibility = System.Windows.Visibility.Visible;
                //adControl.IsAutoRefreshEnabled = true;
                adControl.IsEnabled             = true;
                adControl.IsAutoCollapseEnabled = false;
            }
            else
            {
                // disables ads
                adControl.Visibility = System.Windows.Visibility.Collapsed;
                //adControl.IsAutoRefreshEnabled = false;
                adControl.IsEnabled             = false;
                adControl.IsAutoCollapseEnabled = false;
            }
            #endregion


            OrientationChanged += new EventHandler <OrientationChangedEventArgs>(MainPage_OrientationChanged);

            // initially check
            PageOrientation po = this.Orientation;
            if (po == PageOrientation.Portrait || po == PageOrientation.PortraitDown || po == PageOrientation.PortraitUp)
            {
                // return pivot to original position
                MapHeight           = 800;
                MainPivot.Margin    = new Thickness(0, 125, 0, 0);
                AllPivot.Header     = "all";
                FreewayPivot.Header = "highways";
                RoadPivot.Header    = "roads";

                // this.ApplicationBar.IsVisible = this.ApplicationBar.IsVisible;
            }
            else if (po == PageOrientation.Landscape || po == PageOrientation.LandscapeLeft || po == PageOrientation.LandscapeRight)
            {
                // hiding pivot header in landscape mode
                MapHeight           = 480;
                MainPivot.Margin    = new Thickness(0, 30, 0, 0);
                AllPivot.Header     = "";
                FreewayPivot.Header = "";
                RoadPivot.Header    = "";
                //    this.ApplicationBar.IsVisible = !this.ApplicationBar.IsVisible;
            }



            isolatedStorageSettings = IsolatedStorageSettings.ApplicationSettings;


            // disable lock screen timer
            Microsoft.Phone.Shell.PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;

            // References:
            // http://weblogs.asp.net/scottgu/archive/2010/03/18/building-a-windows-phone-7-twitter-application-using-silverlight.aspx
            // http://msdn.microsoft.com/en-us/library/hh441726.aspx
            // http://json.codeplex.com
            // Bing Maps REST Services API Reference: http://msdn.microsoft.com/en-us/library/ff701722.aspx
            // Adding Tile Layers (overlays) http://msdn.microsoft.com/en-us/library/ee681902.aspx

            wc = new WebClient();
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(REST_traffic);
            //wc.DownloadStringAsync(new Uri("http://dev.virtualearth.net/REST/v1/Traffic/Incidents/37,-105,45,-94?key=" + Id));

            // caching
            Current_Location.CacheMode = new BitmapCache();
            mMap.ZoomLevel             = 10;
            //mMap.ZoomBarVisibility = System.Windows.Visibility.Visible;
            Current_Location.Style          = (Style)(Application.Current.Resources["PushpinStyle"]);
            Current_Location.PositionOrigin = PositionOrigin.Center;

            MyPreviousLocation.X = 0; MyPreviousLocation.Y = 0;
            #region Progress Indicator
            SystemTray.SetIsVisible(this, true);
            SystemTray.SetOpacity(this, 0.5);
            SystemTray.SetBackgroundColor(this, Colors.Black);
            SystemTray.SetForegroundColor(this, Colors.White);
            prog = new ProgressIndicator();
            prog.IsIndeterminate = true;
            prog.IsVisible       = true;
            SystemTray.SetProgressIndicator(this, prog);

            #endregion
        }
Example #55
0
        /// <summary>
        /// Fill sheet rows for Type sheet
        /// </summary>
        /// <returns>COBieSheet</returns>
        public override COBieSheet <COBieTypeRow> Fill()
        {
#if DEBUG
            Stopwatch timer = new Stopwatch();
            timer.Start();
#endif
            ProgressIndicator.ReportMessage("Starting Types...");

            // Create new Sheet
            COBieSheet <COBieTypeRow> types = new COBieSheet <COBieTypeRow>(Constants.WORKSHEET_TYPE);

            //group the types by name as we need to filter duplicate items in for each loop
            IEnumerable <IfcTypeObject> ifcTypeObjects = Model.Instances.OfType <IfcTypeObject>()
                                                         .Select(type => type)
                                                         .Where(type => !Context.Exclude.ObjectType.Types.Contains(type.GetType()))
                                                         .GroupBy(type => type.Name).SelectMany(g => g);//.Distinct()



            //set up property set helper class
            COBieDataPropertySetValues allPropertyValues = new COBieDataPropertySetValues(); //properties helper class
            COBieDataAttributeBuilder  attributeBuilder  = new COBieDataAttributeBuilder(Context, allPropertyValues);
            attributeBuilder.InitialiseAttributes(ref _attributes);
            attributeBuilder.ExcludeAttributePropertyNames.AddRange(Context.Exclude.Types.AttributesEqualTo);         //we do not want for the attribute sheet so filter them out
            attributeBuilder.ExcludeAttributePropertyNamesWildcard.AddRange(Context.Exclude.Types.AttributesContain); //we do not want for the attribute sheet so filter them out
            attributeBuilder.ExcludeAttributePropertySetNames.AddRange(Context.Exclude.Types.PropertySetsEqualTo);    //exclude the property set from selection of values
            attributeBuilder.RowParameters["Sheet"] = "Type";

            ProgressIndicator.Initialise("Creating Types", ifcTypeObjects.Count());
            //COBieTypeRow lastRow = null;
            foreach (IfcTypeObject type in ifcTypeObjects)
            {
                ProgressIndicator.IncrementAndUpdate();


                COBieTypeRow typeRow = new COBieTypeRow(types);

                // TODO: Investigate centralising this common code.
                string name = type.Name;
                if (string.IsNullOrEmpty(type.Name))
                {
                    name = "Name Unknown " + UnknownCount.ToString();
                    UnknownCount++;
                }

                //set allPropertyValues to this element
                allPropertyValues.SetAllPropertyValues(type); //set the internal filtered IfcPropertySingleValues List in allPropertyValues

                typeRow.Name = name;
                string create_By = allPropertyValues.GetPropertySingleValueValue("COBieTypeCreatedBy", false);  //support for COBie Toolkit for Autodesk Revit
                typeRow.CreatedBy = ValidateString(create_By) ? create_By : GetTelecomEmailAddress(type.OwnerHistory);
                string created_On = allPropertyValues.GetPropertySingleValueValue("COBieTypeCreatedOn", false); //support for COBie Toolkit for Autodesk Revit
                typeRow.CreatedOn = ValidateString(created_On) ? created_On : GetCreatedOnDateAsFmtString(type.OwnerHistory);
                typeRow.Category  = GetCategory(allPropertyValues);
                string description = allPropertyValues.GetPropertySingleValueValue("COBieDescription", false);//support for COBie Toolkit for Autodesk Revit
                typeRow.Description = ValidateString(description) ? description : GetTypeObjDescription(type);

                string ext_System = allPropertyValues.GetPropertySingleValueValue("COBieTypeExtSystem", false);//support for COBie Toolkit for Autodesk Revit
                typeRow.ExtSystem     = ValidateString(ext_System) ? ext_System : GetExternalSystem(type);
                typeRow.ExtObject     = type.GetType().Name;
                typeRow.ExtIdentifier = type.GlobalId;



                FillPropertySetsValues(allPropertyValues, type, typeRow);
                //not duplicate so add to sheet
                //if (CheckForDuplicateRow(lastRow, typeRow))
                //{
                string rowhash = typeRow.RowHashValue;
                if (RowHashs.ContainsKey(rowhash))
                {
                    continue;
                }
                else
                {
                    types.AddRow(typeRow);
                    RowHashs.Add(rowhash, true);
                }

                //lastRow = typeRow; //save this row to test on next loop
                //}
                // Provide Attribute sheet with our context
                //fill in the attribute information
                attributeBuilder.RowParameters["Name"]      = typeRow.Name;
                attributeBuilder.RowParameters["CreatedBy"] = typeRow.CreatedBy;
                attributeBuilder.RowParameters["CreatedOn"] = typeRow.CreatedOn;
                attributeBuilder.RowParameters["ExtSystem"] = typeRow.ExtSystem;
                attributeBuilder.PopulateAttributesRows(type); //fill attribute sheet rows
            }
            ProgressIndicator.Finalise();
            //--------------Loop all IfcMaterialLayerSet-----------------------------
            ProgressIndicator.ReportMessage("Starting MaterialLayerSets...");
            IEnumerable <IfcMaterialLayerSet> ifcMaterialLayerSets = Model.Instances.OfType <IfcMaterialLayerSet>();
            ChildNamesList rowHolderChildNames      = new ChildNamesList();
            ChildNamesList rowHolderLayerChildNames = new ChildNamesList();

            string createdBy = DEFAULT_STRING, createdOn = DEFAULT_STRING, extSystem = DEFAULT_STRING;
            ProgressIndicator.Initialise("Creating MaterialLayerSets", ifcMaterialLayerSets.Count());

            foreach (IfcMaterialLayerSet ifcMaterialLayerSet in ifcMaterialLayerSets)
            {
                ProgressIndicator.IncrementAndUpdate();
                //Material layer has no owner history, so lets take the owner history from IfcRelAssociatesMaterial.RelatingMaterial -> (IfcMaterialLayerSetUsage.ForLayerSet -> IfcMaterialLayerSet) || IfcMaterialLayerSet || IfcMaterialLayer as it is a IfcMaterialSelect
                IfcOwnerHistory ifcOwnerHistory = GetMaterialOwnerHistory(ifcMaterialLayerSet);
                if (ifcOwnerHistory != null)
                {
                    createdBy = GetTelecomEmailAddress(ifcOwnerHistory);
                    createdOn = GetCreatedOnDateAsFmtString(ifcOwnerHistory);
                    extSystem = GetExternalSystem(ifcOwnerHistory);
                }
                else //default to the project as we failed to find a IfcRoot object to extract it from
                {
                    createdBy = GetTelecomEmailAddress(Model.IfcProject.OwnerHistory);
                    createdOn = GetCreatedOnDateAsFmtString(Model.IfcProject.OwnerHistory);
                    extSystem = GetExternalSystem(Model.IfcProject.OwnerHistory);
                }
                //add materialLayerSet name to rows
                COBieTypeRow matSetRow = new COBieTypeRow(types);
                matSetRow.Name      = (string.IsNullOrEmpty(ifcMaterialLayerSet.Name)) ? DEFAULT_STRING : ifcMaterialLayerSet.Name;
                matSetRow.CreatedBy = createdBy;
                matSetRow.CreatedOn = createdOn;
                matSetRow.ExtSystem = extSystem;
                matSetRow.ExtObject = ifcMaterialLayerSet.GetType().Name;
                matSetRow.AssetType = "Fixed";
                types.AddRow(matSetRow);

                //loop the materials within the material layer set
                foreach (IfcMaterialLayer ifcMaterialLayer in ifcMaterialLayerSet.MaterialLayers)
                {
                    if ((ifcMaterialLayer.Material != null) &&
                        (!string.IsNullOrEmpty(ifcMaterialLayer.Material.Name))
                        )
                    {
                        string name      = ifcMaterialLayer.Material.Name.ToString().Trim();
                        double thickness = ifcMaterialLayer.LayerThickness;
                        string keyName   = name + " (" + thickness.ToString() + ")";
                        if (!rowHolderLayerChildNames.Contains(keyName.ToLower())) //check we do not already have it
                        {
                            COBieTypeRow matRow = new COBieTypeRow(types);

                            matRow.Name         = keyName;
                            matRow.CreatedBy    = createdBy;
                            matRow.CreatedOn    = createdOn;
                            matRow.ExtSystem    = extSystem;
                            matRow.ExtObject    = ifcMaterialLayer.GetType().Name;
                            matRow.AssetType    = "Fixed";
                            matRow.NominalWidth = thickness.ToString();

                            rowHolderLayerChildNames.Add(keyName.ToLower());

                            //we also don't want to repeat on the IfcMaterial loop below
                            if (!rowHolderChildNames.Contains(name.ToLower()))
                            {
                                rowHolderChildNames.Add(name.ToLower());
                            }

                            types.AddRow(matRow);
                        }
                    }
                }
            }
            ProgressIndicator.Finalise();
            //--------Loop Materials in case they are not in a layer Set-----
            ProgressIndicator.ReportMessage("Starting Materials...");

            IEnumerable <IfcMaterial> ifcMaterials = Model.Instances.OfType <IfcMaterial>();
            ProgressIndicator.Initialise("Creating Materials", ifcMaterials.Count());
            foreach (IfcMaterial ifcMaterial in ifcMaterials)
            {
                ProgressIndicator.IncrementAndUpdate();
                string name = ifcMaterial.Name.ToString().Trim();
                if (!string.IsNullOrEmpty(ifcMaterial.Name))
                {
                    if (!rowHolderChildNames.Contains(name.ToLower())) //check we do not already have it
                    {
                        COBieTypeRow matRow = new COBieTypeRow(types);

                        matRow.Name      = name;
                        matRow.CreatedBy = createdBy; //no way of extraction on material, if no material layer set, so use last found in Layer Set loop
                        matRow.CreatedOn = createdOn; //ditto
                        matRow.ExtSystem = extSystem; //ditto
                        matRow.ExtObject = ifcMaterial.GetType().Name;
                        matRow.AssetType = "Fixed";

                        types.AddRow(matRow);
                    }

                    rowHolderChildNames.Add(name.ToLower());
                }
            }

            types.OrderBy(s => s.Name);

            ProgressIndicator.Finalise();

#if DEBUG
            timer.Stop();
            Console.WriteLine(String.Format("Time to generate Type data = {0} seconds", timer.Elapsed.TotalSeconds.ToString("F3")));
#endif
            return(types);
        }
Example #56
0
        /// <summary>
        /// Fill sheet rows for Contact sheet
        /// </summary>
        /// <returns>COBieSheet</returns>
        public override COBieSheet <COBieContactRow> Fill()
        {
            ProgressIndicator.ReportMessage("Starting Contacts...");

            ClearEMails(); //clear the email dictionary for a new file conversion

            //create new sheet
            COBieSheet <COBieContactRow>           contacts                  = new COBieSheet <COBieContactRow>(Constants.WORKSHEET_CONTACT);
            IEnumerable <string>                   cobieContacts             = Model.Instances.OfType <IfcPropertySingleValue>().Where(psv => psv.Name == "COBieCreatedBy" || psv.Name == "COBieTypeCreatedBy").GroupBy(psv => psv.NominalValue).Select(g => g.First().NominalValue.ToString());
            IEnumerable <IfcPersonAndOrganization> ifcPersonAndOrganizations = Model.Instances.OfType <IfcPersonAndOrganization>();

            ProgressIndicator.Initialise("Creating Contacts", ifcPersonAndOrganizations.Count() + cobieContacts.Count());

            List <IfcOrganizationRelationship> ifcOrganizationRelationships = null;

            foreach (IfcPersonAndOrganization ifcPersonAndOrganization in ifcPersonAndOrganizations)
            {
                ProgressIndicator.IncrementAndUpdate();

                //check we do not have a default email address, if skip it as we want the validation warning
                string email = GetTelecomEmailAddress(ifcPersonAndOrganization);
                if (email == Constants.DEFAULT_EMAIL)
                {
                    continue;
                }

                COBieContactRow contact = new COBieContactRow(contacts);
                // get person and organization
                IfcOrganization ifcOrganization = ifcPersonAndOrganization.TheOrganization;
                IfcPerson       ifcPerson       = ifcPersonAndOrganization.ThePerson;
                contact.Email = email;

                //lets default the creator to that user who created the project for now, no direct link to OwnerHistory on IfcPersonAndOrganization, IfcPerson or IfcOrganization
                contact.CreatedBy = GetTelecomEmailAddress(Model.IfcProject.OwnerHistory);
                contact.CreatedOn = GetCreatedOnDateAsFmtString(Model.IfcProject.OwnerHistory);

                IfcActorRole ifcActorRole = null;
                if (ifcPerson.Roles != null)
                {
                    ifcActorRole = ifcPerson.Roles.FirstOrDefault();
                }
                if (ifcOrganization.Roles != null)
                {
                    ifcActorRole = ifcOrganization.Roles.FirstOrDefault();
                }
                if ((ifcActorRole != null) && (!string.IsNullOrEmpty(ifcActorRole.UserDefinedRole)))
                {
                    contact.Category = ifcActorRole.UserDefinedRole.ToString();
                }
                else
                {
                    contact.Category = DEFAULT_STRING;
                }

                contact.Company   = (string.IsNullOrEmpty(ifcOrganization.Name)) ? DEFAULT_STRING : ifcOrganization.Name.ToString();
                contact.Phone     = GetTelecomTelephoneNumber(ifcPersonAndOrganization);
                contact.ExtSystem = DEFAULT_STRING;   // TODO: Person is not a Root object so has no Owner. What should this be?

                contact.ExtObject = "IfcPersonAndOrganization";
                if (!string.IsNullOrEmpty(ifcPerson.Id))
                {
                    contact.ExtIdentifier = ifcPerson.Id;
                }
                //get department
                string department = "";
                if (ifcPerson.Addresses != null)
                {
                    department = ifcPerson.Addresses.PostalAddresses.Select(dept => dept.InternalLocation).Where(dept => !string.IsNullOrEmpty(dept)).FirstOrDefault();
                }
                if (string.IsNullOrEmpty(department))
                {
                    if (ifcOrganizationRelationships == null)
                    {
                        ifcOrganizationRelationships = Model.Instances.OfType <IfcOrganizationRelationship>().ToList();
                    }
                    IfcOrganization ifcRelOrganization = ifcOrganizationRelationships
                                                         .Where(Or => Or.RelatingOrganization.EntityLabel == ifcOrganization.EntityLabel && Or.RelatedOrganizations.Last() != null)
                                                         .Select(Or => Or.RelatedOrganizations.Last())
                                                         .LastOrDefault();
                    if (ifcRelOrganization != null)
                    {
                        department = ifcRelOrganization.Name.ToString();
                    }
                }
                if (string.IsNullOrEmpty(department))
                {
                    department = ifcOrganization.Description.ToString(); //only place to match example files
                }
                contact.Department = (string.IsNullOrEmpty(department)) ? contact.Company : department;

                contact.OrganizationCode = (string.IsNullOrEmpty(ifcOrganization.Id)) ? DEFAULT_STRING : ifcOrganization.Id.ToString();
                contact.GivenName        = (string.IsNullOrEmpty(ifcPerson.GivenName)) ? DEFAULT_STRING : ifcPerson.GivenName.ToString();
                contact.FamilyName       = (string.IsNullOrEmpty(ifcPerson.FamilyName)) ? DEFAULT_STRING : ifcPerson.FamilyName.ToString();
                if (ifcPerson.Addresses != null)
                {
                    GetContactAddress(contact, ifcPerson.Addresses);
                }
                else
                {
                    GetContactAddress(contact, ifcOrganization.Addresses);
                }

                contacts.AddRow(contact);
            }

            foreach (string email in cobieContacts)
            {
                ProgressIndicator.IncrementAndUpdate();
                COBieContactRow contact = new COBieContactRow(contacts);
                contact.Email = email;

                //lets default the creator to that user who created the project for now, no direct link to OwnerHistory on IfcPersonAndOrganization, IfcPerson or IfcOrganization
                contact.CreatedBy = GetTelecomEmailAddress(Model.IfcProject.OwnerHistory);
                contact.CreatedOn = GetCreatedOnDateAsFmtString(Model.IfcProject.OwnerHistory);
                contact.Category  = DEFAULT_STRING;
                contact.Company   = DEFAULT_STRING;
                contact.Phone     = DEFAULT_STRING;
                contact.ExtSystem = DEFAULT_STRING;

                contact.ExtObject  = "IfcPropertySingleValue";
                contact.Department = DEFAULT_STRING;

                contact.OrganizationCode = DEFAULT_STRING;
                contact.GivenName        = DEFAULT_STRING;
                contact.FamilyName       = DEFAULT_STRING;
                contact.Street           = DEFAULT_STRING;
                contact.PostalBox        = DEFAULT_STRING;
                contact.Town             = DEFAULT_STRING;
                contact.StateRegion      = DEFAULT_STRING;
                contact.PostalCode       = DEFAULT_STRING;
                contact.Country          = DEFAULT_STRING;

                contacts.AddRow(contact);
            }
            ProgressIndicator.Finalise();

            contacts.OrderBy(s => s.Email);

            return(contacts);
        }
        /// <summary>
        /// Fill sheet rows for Component sheet
        /// </summary>
        /// <returns>COBieSheet</returns>
        public override COBieSheet <COBieComponentRow> Fill()
        {
#if DEBUG
            Stopwatch timer = new Stopwatch();
            timer.Start();
#endif
            ProgressIndicator.ReportMessage("Starting Components...");
            //Create new sheet
            COBieSheet <COBieComponentRow> components = new COBieSheet <COBieComponentRow>(Constants.WORKSHEET_COMPONENT);



            IEnumerable <IfcRelAggregates> relAggregates = Model.Instances.OfType <IfcRelAggregates>();
            IEnumerable <IfcRelContainedInSpatialStructure> relSpatial = Model.Instances.OfType <IfcRelContainedInSpatialStructure>();

            IEnumerable <IfcObject> ifcElements = ((from x in relAggregates
                                                    from y in x.RelatedObjects
                                                    where !Context.Exclude.ObjectType.Component.Contains(y.GetType())
                                                    select y).Union(from x in relSpatial
                                                                    from y in x.RelatedElements
                                                                    where !Context.Exclude.ObjectType.Component.Contains(y.GetType())
                                                                    select y)).OfType <IfcObject>(); //.GroupBy(el => el.Name).Select(g => g.First())//.Distinct().ToList();

            COBieDataPropertySetValues allPropertyValues = new COBieDataPropertySetValues();         //properties helper class
            COBieDataAttributeBuilder  attributeBuilder  = new COBieDataAttributeBuilder(Context, allPropertyValues);
            attributeBuilder.InitialiseAttributes(ref _attributes);
            //set up filters on COBieDataPropertySetValues for the SetAttributes only
            attributeBuilder.ExcludeAttributePropertyNames.AddRange(Context.Exclude.Component.AttributesEqualTo);         //we do not want listed properties for the attribute sheet so filter them out
            attributeBuilder.ExcludeAttributePropertyNamesWildcard.AddRange(Context.Exclude.Component.AttributesContain); //we do not want listed properties for the attribute sheet so filter them out
            attributeBuilder.RowParameters["Sheet"] = "Component";


            ProgressIndicator.Initialise("Creating Components", ifcElements.Count());

            foreach (var obj in ifcElements)
            {
                ProgressIndicator.IncrementAndUpdate();

                COBieComponentRow component = new COBieComponentRow(components);

                IfcElement el = obj as IfcElement;
                if (el == null)
                {
                    continue;
                }
                string name = el.Name.ToString();
                if (string.IsNullOrEmpty(name))
                {
                    name = "Name Unknown " + UnknownCount.ToString();
                    UnknownCount++;
                }
                //set allPropertyValues to this element
                allPropertyValues.SetAllPropertyValues(el); //set the internal filtered IfcPropertySingleValues List in allPropertyValues
                component.Name = name;

                string createBy = allPropertyValues.GetPropertySingleValueValue("COBieCreatedBy", false);  //support for COBie Toolkit for Autodesk Revit
                component.CreatedBy = ValidateString(createBy) ? createBy : GetTelecomEmailAddress(el.OwnerHistory);
                string createdOn = allPropertyValues.GetPropertySingleValueValue("COBieCreatedOn", false); //support for COBie Toolkit for Autodesk Revit
                component.CreatedOn = ValidateString(createdOn) ?  createdOn : GetCreatedOnDateAsFmtString(el.OwnerHistory);

                component.TypeName = GetTypeName(el);
                component.Space    = GetComponentRelatedSpace(el);
                string description = allPropertyValues.GetPropertySingleValueValue("COBieDescription", false); //support for COBie Toolkit for Autodesk Revit
                component.Description = ValidateString(description) ? description : GetComponentDescription(el);
                string extSystem = allPropertyValues.GetPropertySingleValueValue("COBieExtSystem", false);     //support for COBie Toolkit for Autodesk Revit
                component.ExtSystem     = ValidateString(extSystem) ? extSystem : GetExternalSystem(el);
                component.ExtObject     = el.GetType().Name;
                component.ExtIdentifier = el.GlobalId;

                //set from PropertySingleValues filtered via candidateProperties
                //set the internal filtered IfcPropertySingleValues List in allPropertyValues to this element set above
                component.SerialNumber      = allPropertyValues.GetPropertySingleValueValue("SerialNumber", false);
                component.InstallationDate  = GetDateFromProperty(allPropertyValues, "InstallationDate");
                component.WarrantyStartDate = GetDateFromProperty(allPropertyValues, "WarrantyStartDate");
                component.TagNumber         = allPropertyValues.GetPropertySingleValueValue("TagNumber", false);
                component.BarCode           = allPropertyValues.GetPropertySingleValueValue("BarCode", false);
                component.AssetIdentifier   = allPropertyValues.GetPropertySingleValueValue("AssetIdentifier", false);

                components.AddRow(component);

                //fill in the attribute information
                attributeBuilder.RowParameters["Name"]      = component.Name;
                attributeBuilder.RowParameters["CreatedBy"] = component.CreatedBy;
                attributeBuilder.RowParameters["CreatedOn"] = component.CreatedOn;
                attributeBuilder.RowParameters["ExtSystem"] = component.ExtSystem;
                attributeBuilder.PopulateAttributesRows(el); //fill attribute sheet rows
            }

            components.OrderBy(s => s.Name);

            ProgressIndicator.Finalise();
#if DEBUG
            timer.Stop();
            Console.WriteLine(String.Format("Time to generate Component data = {0} seconds", timer.Elapsed.TotalSeconds.ToString("F3")));
#endif


            return(components);
        }
        public PluginRegistrationForm(CrmOrganization org, MainControl orgControl, CrmPluginAssembly assembly)
        {
            if (org == null)
            {
                throw new ArgumentNullException("org");
            }
            else if (orgControl == null)
            {
                throw new ArgumentNullException("orgControl");
            }

            InitializeComponent();

            m_org              = org;
            m_orgControl       = orgControl;
            m_progRegistration = new ProgressIndicator(ProgressIndicatorInit, ProgressIndicatorComplete,
                                                       ProgressIndicatorAddText, ProgressIndicatorSetText,
                                                       ProgressIndicatorIncrement, null);
            m_currentAssembly = assembly;

            trvPlugins.CrmTreeNodeSorter = orgControl.CrmTreeNodeSorter;

            //Check if this is a known assembly
            if (null == assembly)
            {
                //If this is a known assembly, check for the default isolation mode for each authentication type
                if (null != org.ConnectionDetail)
                {
                    // TODO: Come back
                    //switch (org.ConnectionDetail.GetDiscoveryService().ServiceConfiguration.AuthenticationType)
                    //{
                    //    case Microsoft.Xrm.Sdk.Client.AuthenticationProviderType.ActiveDirectory:
                    //        radIsolationNone.Checked = true;
                    //        break;
                    //    default:
                    //        radIsolationSandbox.Checked = true;
                    //        break;
                    //}
                }
            }
            else
            {
                m_registeredPluginList = new List <CrmPlugin>();

                LoadAssembly(assembly, false);

                switch (assembly.IsolationMode)
                {
                case CrmAssemblyIsolationMode.Sandbox:
                    radIsolationSandbox.Checked = true;
                    break;

                case CrmAssemblyIsolationMode.None:
                    radIsolationNone.Checked = true;
                    break;

                default:
                    throw new NotImplementedException("IsolationMode = " + assembly.IsolationMode.ToString());
                }

                switch (assembly.SourceType)
                {
                case CrmAssemblySourceType.Database:
                    radDB.Checked = true;
                    break;

                case CrmAssemblySourceType.Disk:
                    radDisk.Checked = true;
                    break;

                case CrmAssemblySourceType.GAC:
                    radGAC.Checked = true;
                    break;

                default:
                    throw new NotImplementedException("SourceType = " + assembly.SourceType.ToString());
                }

                txtServerFileName.Text = assembly.ServerFileName;

                Text             = string.Format("Update Assembly: {0}", assembly.Name);
                btnRegister.Text = "Update Selected Plugins";
            }

            EnableRegistrationControls();
        }
Example #59
0
        static int DoStuff(ArgumentParser.LogDumpOptions opts)
        {
            List <string> files = new List <string>();

            if (opts.InputFiles.Count() > 0) // did the user give us a list of files?
            {
                List <string> problems = new List <string>();
                files = opts.InputFiles.ToList();

                // check if the list provided contains only .raw files
                foreach (string file in files)
                {
                    if (!file.EndsWith(".raw", StringComparison.OrdinalIgnoreCase))
                    {
                        problems.Add(file);
                    }
                }

                if (problems.Count() == 1)
                {
                    Console.WriteLine("\nERROR: {0} does not appear to be a .raw file. Invoke '>RawTools --help' if you need help.", problems.ElementAt(0));
                    Log.Error("Invalid file provided: {0}", problems.ElementAt(0));

                    return(1);
                }

                if (problems.Count() > 1)
                {
                    Console.WriteLine("\nERROR: The following {0} files do not appear to be .raw files. Invoke '>RawTools --help' if you need help." +
                                      "\n\n{1}", problems.Count(), String.Join("\n", problems));
                    Log.Error("Invalid files provided: {0}", String.Join(" ", problems));
                    return(1);
                }

                Log.Information("Files to be processed, provided as list: {0}", String.Join(" ", files));
            }

            else // did the user give us a directory?
            {
                if (Directory.Exists(opts.InputDirectory))
                {
                    files = Directory.GetFiles(opts.InputDirectory, "*.*", SearchOption.TopDirectoryOnly)
                            .Where(s => s.EndsWith(".raw", StringComparison.OrdinalIgnoreCase)).ToList();
                }
                else
                {
                    Console.WriteLine("ERROR: The provided directory does not appear to be valid.");
                    Log.Error("Invalid directory provided: {0}", opts.InputDirectory);
                    return(1);
                }

                Log.Information("Files to be processed, provided as directory: {0}", String.Join(" ", files));
            }

            Console.WriteLine();

            foreach (var file in files)
            {
                Console.WriteLine(Path.GetFileName(file));
                Console.WriteLine("----------------------------------------");
                using (IRawDataPlus rawFile = RawFileReaderFactory.ReadFile(file))
                {
                    rawFile.SelectMsData();

                    var numberOfLogs = rawFile.GetStatusLogEntriesCount();
                    var logInfo      = rawFile.GetStatusLogHeaderInformation();

                    string logName = file + ".INST_LOG.txt";

                    Dictionary <int, ISingleValueStatusLog> log = new Dictionary <int, ISingleValueStatusLog>();

                    ProgressIndicator P = new ProgressIndicator(logInfo.Count(), "Preparing log data");
                    P.Start();
                    for (int i = 0; i < logInfo.Count(); i++)
                    {
                        log.Add(i, rawFile.GetStatusLogAtPosition(i));
                        P.Update();
                    }
                    P.Done();

                    using (StreamWriter f = new StreamWriter(logName))
                    {
                        P = new ProgressIndicator(numberOfLogs, $"Writing log");
                        P.Start();
                        f.Write("Time\t");
                        foreach (var x in logInfo)
                        {
                            f.Write(x.Label + "\t");
                        }
                        f.Write("\n");

                        for (int i = 0; i < numberOfLogs; i++)
                        {
                            f.Write($"{log[0].Times[i]}\t");

                            for (int j = 0; j < logInfo.Length; j++)
                            {
                                try
                                {
                                    f.Write("{0}\t", log[j].Values[i]);
                                }
                                catch (Exception)
                                {
                                    f.Write("\t");
                                }
                            }
                            f.Write("\n");
                            P.Update();
                        }
                        P.Done();
                    }
                }
                Console.WriteLine("\n");
            }
            return(0);
        }
Example #60
0
        void ReleaseDesignerOutlets()
        {
            if (ColorIndicator != null)
            {
                ColorIndicator.Dispose();
                ColorIndicator = null;
            }

            if (ErrorLabel != null)
            {
                ErrorLabel.Dispose();
                ErrorLabel = null;
            }

            if (ImageCell != null)
            {
                ImageCell.Dispose();
                ImageCell = null;
            }

            if (NodeEditorButton != null)
            {
                NodeEditorButton.Dispose();
                NodeEditorButton = null;
            }

            if (PausePlayButton != null)
            {
                PausePlayButton.Dispose();
                PausePlayButton = null;
            }

            if (ProgressIndicator != null)
            {
                ProgressIndicator.Dispose();
                ProgressIndicator = null;
            }

            if (RandomImageButton != null)
            {
                RandomImageButton.Dispose();
                RandomImageButton = null;
            }

            if (RandomImageSpinner != null)
            {
                RandomImageSpinner.Dispose();
                RandomImageSpinner = null;
            }

            if (ScaleChooser != null)
            {
                ScaleChooser.Dispose();
                ScaleChooser = null;
            }

            if (StopButton != null)
            {
                StopButton.Dispose();
                StopButton = null;
            }
        }