Exemple #1
0
        private static IAccount Create(string name)
        {
            AccountElement accoutConfig = Config(name);

            if (accoutConfig == null)
            {
                throw new ArgumentException("unknown account configuration \"" + name + "\"");
            }

            IDictionary <string, string> options = new Dictionary <string, string>();

            foreach (KeyValueConfigurationElement kv in accoutConfig.Options)
            {
                options.Add(kv.Key, kv.Value);
            }

            BaseAccount ret = null;

            string[] types = accoutConfig.Type.Split('+');

            Array.Reverse(types);
            foreach (string t in types)
            {
                ret = AccountManager.Create(name, t, options, ret);
            }

            return(ret);
        }
        /// <summary>
        /// Called when the accounts need to be populated
        /// </summary>
        /// <returns>The accounts.</returns>
        protected List<AccountElement> PopulateAccounts()
        {
            var accounts = new List<AccountElement>();
            var accountsService = Mvx.Resolve<IAccountsService>();

            foreach (var account in accountsService)
            {
                var thisAccount = account;
                var t = new AccountElement(thisAccount);
                t.Tapped += () =>
                {
                    if (accountsService.ActiveAccount != null && accountsService.ActiveAccount.Id == thisAccount.Id)
                        DismissViewController(true, null);
                    else
                        ViewModel.SelectAccountCommand.Execute(thisAccount);
                };

                //Check to see if this account is the active account. Application.Account could be null 
                //so make it the target of the equals, not the source.
                if (thisAccount.Equals(accountsService.ActiveAccount))
                    t.Accessory = UITableViewCellAccessory.Checkmark;
                accounts.Add(t);
            }
            return accounts;
        }
Exemple #3
0
        /// <summary>
        /// Called when the accounts need to be populated
        /// </summary>
        /// <returns>The accounts.</returns>
        protected List <AccountElement> PopulateAccounts()
        {
            var accounts        = new List <AccountElement>();
            var accountsService = Mvx.Resolve <IAccountsService>();

            foreach (var account in accountsService)
            {
                var thisAccount = account;
                var t           = new AccountElement(thisAccount);
                t.Tapped += () =>
                {
                    if (accountsService.ActiveAccount != null && accountsService.ActiveAccount.Id == thisAccount.Id)
                    {
                        DismissViewController(true, null);
                    }
                    else
                    {
                        ViewModel.SelectAccountCommand.Execute(thisAccount);
                    }
                };

                //Check to see if this account is the active account. Application.Account could be null
                //so make it the target of the equals, not the source.
                if (thisAccount.Equals(accountsService.ActiveAccount))
                {
                    t.Accessory = UITableViewCellAccessory.Checkmark;
                }
                accounts.Add(t);
            }
            return(accounts);
        }
Exemple #4
0
        public bool AddToSchedule(string serviceName, int accountID, DateTime targetTime, Edge.Core.SettingsCollection options)
        {
            AccountElement account = EdgeServicesConfiguration.Current.Accounts.GetAccount(accountID);

            if (account == null)
            {
                Log.Write(Program.LS, String.Format("Ignoring AddToSchedule request for account {0} which does not exist.", accountID), LogMessageType.Warning);
                return(false);
            }

            AccountServiceElement service = account.Services[serviceName];

            if (service == null)
            {
                Log.Write(Program.LS, String.Format("Ignoring AddToSchedule request for service {0} which does not exist in account {1}.", serviceName, accountID), LogMessageType.Warning);
                return(false);
            }

            var             activeServiceElement = new ActiveServiceElement(service);
            ServicePriority priority             = activeServiceElement.Options.ContainsKey("ServicePriority") ?
                                                   (ServicePriority)Enum.Parse(typeof(ServicePriority), activeServiceElement.Options["ServicePriority"]) :
                                                   ServicePriority.Normal;

            AddToSchedule(activeServiceElement, account, targetTime, options, priority);
            return(true);
        }
 public RelationControlViewModel(AccountElement ae, ShowPainKind kind = ShowPainKind.Following)
     :this()
 {
     this.AccSelectedIndex = Elements.TakeWhile(e => e.AccountElement.CredentialInfo.UserScreenName == ae.CredentialInfo.UserScreenName).Count();
     if (this.AccSelectedIndex >= Elements.Count())
         this.AccSelectedIndex = 0;
     this.TabSelectedIndex = (int)kind;
 }
Exemple #6
0
 public DisplayNode(AccountElement account) : this()
 {
     AccountID = account.ID;
     Name      = string.Format("{0} ({1})", account.Name, account.ID);
     foreach (AccountServiceElement service in account.Services)
     {
         Children.Add(new DisplayNode(new ActiveServiceElement(service), accountID: this.AccountID));
     }
     IsExpanded = false;
 }
Exemple #7
0
 public string UploadImage(AccountElement accElement, string path, string comment)
 {
     string url;
     if (!accElement.CredentialInfo.UploadToTwitpic(_appk, comment, path, out url))
     {
         return null;
     }
     else
     {
         return url;
     }
 }
Exemple #8
0
        public void AddToSchedule(ActiveServiceElement activeServiceElement, AccountElement account, DateTime targetTime, Edge.Core.SettingsCollection options, ServicePriority servicePriority)
        {
            if (options != null)
            {
                foreach (string option in options.Keys)
                {
                    activeServiceElement.Options[option] = options[option];
                }
            }

            //base configuration
            var baseConfiguration = new ServiceConfiguration()
            {
                Name                    = activeServiceElement.Name,
                MaxConcurrent           = activeServiceElement.MaxInstances,
                MaxConcurrentPerProfile = activeServiceElement.MaxInstancesPerAccount
            };

            //configuration per profile
            var instanceConfiguration = new ServiceConfiguration()
            {
                BaseConfiguration = baseConfiguration,
                Name                    = activeServiceElement.Name,
                MaxConcurrent           = (activeServiceElement.MaxInstances == 0) ? 9999 : activeServiceElement.MaxInstances,
                MaxConcurrentPerProfile = (activeServiceElement.MaxInstancesPerAccount == 0) ? 9999 : activeServiceElement.MaxInstancesPerAccount,
                LegacyConfiguration     = activeServiceElement
            };

            //scheduling rules
            instanceConfiguration.SchedulingRules.Add(new SchedulingRule()
            {
                Scope             = SchedulingScope.UnPlanned,
                SpecificDateTime  = targetTime,
                MaxDeviationAfter = TimeSpan.FromMinutes(30),
                Hours             = new List <TimeSpan>(),
                GuidForUnplaned   = Guid.NewGuid(),
            });

            instanceConfiguration.SchedulingRules[0].Hours.Add(new TimeSpan(0, 0, 0, 0));

            Profile profile = new Profile()
            {
                ID       = account.ID,
                Name     = account.ID.ToString(),
                Settings = new Dictionary <string, object>()
            };

            profile.Settings.Add("AccountID", account.ID);
            instanceConfiguration.SchedulingProfile = profile;

            _scheduler.AddNewServiceToSchedule(instanceConfiguration);
        }
        /// <summary>
        /// Validate if the account exist in the DB.
        /// </summary>
        /// <param name="account">The account to validate.</param>
        /// <returns>If the account valid or not.</returns>
        private bool ValidateAccount(AccountElement account)
        {
            // Check if the account exist in the DB, account system (value -1 ) we always run.
            if (account.ID != -1 && !IsAccountExist(account.ID))
            {
                // Write to the log.
                Log.Write(String.Format("The account ID {0} don't exist in the DB, can't schedule his services."
                                        , account.ID), LogMessageType.Warning);

                return(false);
            }

            return(true);
        }
Exemple #10
0
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);
            var root = new RootElement(Title);

            var accountSection = new Section("Accounts");

            root.Add(accountSection);
            foreach (var account in Application.Accounts)
            {
                var thisAccount = account;
                var t           = new AccountElement(thisAccount);
                t.Tapped += () => {
                    Application.SetUser(thisAccount);
                    DismissModalViewControllerAnimated(true);
                };

                //Check to see if this account is the active account. Application.Account could be null
                //so make it the target of the equals, not the source.
                if (thisAccount.Equals(Application.Account))
                {
                    t.Accessory = UITableViewCellAccessory.Checkmark;
                }
                accountSection.Add(t);
            }

            var addAccount = new StyledElement("Add Account", () => {
                var ctrl           = new GitHubLoginController();
                ctrl.LoginComplete = (a) => NavigationController.PopToViewController(this, true);
                NavigationController.PushViewController(ctrl, true);
            });

            //addAccount.Image = Images.CommentAdd;
            accountSection.Add(addAccount);

            var supportSection = new Section("Support");

            root.Add(supportSection);
            supportSection.Add(new StyledElement("Feedback & Support", OpenUserVoice));

            var aboutSection = new Section("About", "Thank you for downloading. Enjoy!");

            root.Add(aboutSection);
            aboutSection.Add(new StyledElement("Follow On Twitter", () => UIApplication.SharedApplication.OpenUrl(new NSUrl("https://twitter.com/Codebucketapp"))));
            aboutSection.Add(new StyledElement("Rate This App", () => UIApplication.SharedApplication.OpenUrl(new NSUrl("https://itunes.apple.com/us/app/codebucket/id551531422?mt=8"))));
            aboutSection.Add(new StyledElement("App Version", NSBundle.MainBundle.InfoDictionary.ValueForKey(new NSString("CFBundleVersion")).ToString()));

            //Assign the root
            Root = root;
        }
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            var accountsService = Mvx.Resolve<IAccountsService>();
            var weakVm = new WeakReference<AccountsViewController>(this);
            var accountSection = new Section();
            accountSection.AddAll(accountsService.Select(account =>
            {
                var t = new AccountElement(account, account.Equals(accountsService.ActiveAccount));
                t.Tapped += () => weakVm.Get()?.SelectAccount(account);
                return t;
            }));
            Root.Reset(accountSection);

            SetCancelButton();
        }
        protected override List<AccountElement> PopulateAccounts()
        {
            var accounts = new List<AccountElement>();
            foreach (var account in Application.Accounts)
            {
                var thisAccount = account;
                var t = new AccountElement(thisAccount);
                t.Tapped += () => AccountSelected(thisAccount);

                //Check to see if this account is the active account. Application.Account could be null
                //so make it the target of the equals, not the source.
                if (thisAccount.Equals(Application.Account))
                    t.Accessory = UITableViewCellAccessory.Checkmark;
                accounts.Add(t);
            }
            return accounts;
        }
Exemple #13
0
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            var accountsService = Mvx.Resolve <IAccountsService>();
            var weakVm          = new WeakReference <AccountsViewController>(this);
            var accountSection  = new Section();

            accountSection.AddAll(accountsService.Select(account =>
            {
                var t     = new AccountElement(account, account.Equals(accountsService.ActiveAccount));
                t.Tapped += () => weakVm.Get()?.SelectAccount(account);
                return(t);
            }));
            Root.Reset(accountSection);

            SetCancelButton();
        }
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);
			var root = new RootElement(Title);

            var accountSection = new Section("Accounts");
			root.Add(accountSection);
            foreach (var account in Application.Accounts)
            {
                var thisAccount = account;
				var t = new AccountElement(thisAccount);
                t.Tapped += () => { 
                    Application.SetUser(thisAccount);
                    DismissModalViewControllerAnimated(true);
                };
                
				//Check to see if this account is the active account. Application.Account could be null 
				//so make it the target of the equals, not the source.
                if (thisAccount.Equals(Application.Account))
                    t.Accessory = UITableViewCellAccessory.Checkmark;
                accountSection.Add(t);
            }

            var addAccount = new StyledElement("Add Account", () => {
				var ctrl = new GitHubLoginController();
				ctrl.LoginComplete = (a) => NavigationController.PopToViewController(this, true);
				NavigationController.PushViewController(ctrl, true);
			});
            //addAccount.Image = Images.CommentAdd;
            accountSection.Add(addAccount);

            var supportSection = new Section("Support");
			root.Add (supportSection);
            supportSection.Add(new StyledElement("Feedback & Support", OpenUserVoice));

            var aboutSection = new Section("About", "Thank you for downloading. Enjoy!");
			root.Add(aboutSection);
            aboutSection.Add(new StyledElement("Follow On Twitter", () => UIApplication.SharedApplication.OpenUrl(new NSUrl("https://twitter.com/Codebucketapp"))));
            aboutSection.Add(new StyledElement("Rate This App", () => UIApplication.SharedApplication.OpenUrl(new NSUrl("https://itunes.apple.com/us/app/codebucket/id551531422?mt=8"))));
            aboutSection.Add(new StyledElement("App Version", NSBundle.MainBundle.InfoDictionary.ValueForKey(new NSString("CFBundleVersion")).ToString()));

			//Assign the root
			Root = root;
        }
        /// <summary>
        /// Called when the accounts need to be populated
        /// </summary>
        /// <returns>The accounts.</returns>
        protected List<AccountElement> PopulateAccounts()
        {
            var accounts = new List<AccountElement>();
            var accountsService = Mvx.Resolve<IAccountsService>();

            foreach (var account in accountsService)
            {
                var thisAccount = account;
                var t = new AccountElement(thisAccount);
                t.Clicked.Select(x => thisAccount).BindCommand(ViewModel.SelectAccountCommand);

                //Check to see if this account is the active account. Application.Account could be null 
                //so make it the target of the equals, not the source.
                if (thisAccount.Equals(accountsService.ActiveAccount))
                    t.Accessory = UITableViewCellAccessory.Checkmark;
                accounts.Add(t);
            }
            return accounts;
        }
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            var weakVm         = new WeakReference <AccountsViewController>(this);
            var accountSection = new Section();

            var activeAccount = _accountsService.GetActiveAccount().Result;

            accountSection.AddAll(_accountsService.GetAccounts().Result.Select(account =>
            {
                var isEqual = account.Id == activeAccount?.Id;
                var t       = new AccountElement(account, isEqual);
                t.Tapped   += () => weakVm.Get()?.SelectAccount(account);
                return(t);
            }));
            Root.Reset(accountSection);

            SetCancelButton();
        }
Exemple #17
0
        /// <summary>
        /// Called when the accounts need to be populated
        /// </summary>
        /// <returns>The accounts.</returns>
        protected List <AccountElement> PopulateAccounts()
        {
            var accounts        = new List <AccountElement>();
            var accountsService = Mvx.Resolve <IAccountsService>();

            foreach (var account in accountsService)
            {
                var thisAccount = account;
                var t           = new AccountElement(thisAccount);
                t.Clicked.Select(x => thisAccount).BindCommand(ViewModel.SelectAccountCommand);

                //Check to see if this account is the active account. Application.Account could be null
                //so make it the target of the equals, not the source.
                if (thisAccount.Equals(accountsService.ActiveAccount))
                {
                    t.Accessory = UITableViewCellAccessory.Checkmark;
                }
                accounts.Add(t);
            }
            return(accounts);
        }
Exemple #18
0
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            var accountsService = Mvx.Resolve <IAccountsService>();
            var weakVm          = new WeakReference <AccountsViewController>(this);
            var accountSection  = new Section();

            accountSection.AddAll(accountsService.Select(account =>
            {
                var t     = new AccountElement(account, account.Equals(accountsService.ActiveAccount));
                t.Tapped += () => weakVm.Get()?.SelectAccount(account);
                return(t);
            }));
            Root.Reset(accountSection);

            if (NavigationItem.LeftBarButtonItem != null)
            {
                NavigationItem.LeftBarButtonItem.Enabled = Root.Sum(x => x.Elements.Count) > 0;
            }
        }
Exemple #19
0
        private void addBtn_Click(object sender, EventArgs e)
        {
            bool allSucceed = true;

            try
            {
                ServicePriority servicePriority      = ServicePriority.Low;
                Edge.Core.SettingsCollection options = new Edge.Core.SettingsCollection();
                DateTime targetDateTime = new DateTime(dateToRunPicker.Value.Year, dateToRunPicker.Value.Month, dateToRunPicker.Value.Day, timeToRunPicker.Value.Hour, timeToRunPicker.Value.Minute, 0);
                bool     result         = false;

                if (priorityCmb.SelectedItem != null)
                {
                    switch (priorityCmb.SelectedItem.ToString())
                    {
                    case "Low":
                    {
                        servicePriority = ServicePriority.Low;
                        break;
                    }

                    case "Normal":
                    {
                        servicePriority = ServicePriority.Normal;
                        break;
                    }

                    case "High":
                    {
                        servicePriority = ServicePriority.High;
                        break;
                    }

                    case "Immediate":
                    {
                        servicePriority = ServicePriority.Immediate;
                        break;
                    }
                    }
                }
                int countedSelectedServices = 0;
                foreach (TreeNode accountNode in servicesTreeView.Nodes)
                {
                    foreach (TreeNode serviceNode in accountNode.Nodes)
                    {
                        if (serviceNode.Checked)
                        {
                            countedSelectedServices++;
                            AccountElement       account = (AccountElement)accountNode.Tag;
                            ActiveServiceElement service = (ActiveServiceElement)serviceNode.Tag;
                            if (useOptionsCheckBox.Checked)
                            {
                                foreach (ListViewItem item in optionsListView.Items)
                                {
                                    options.Add(item.SubItems[0].Text.Trim(), item.SubItems[1].Text.Trim());
                                }

                                DateTime from = FromPicker.Value;
                                DateTime to   = toPicker.Value;
                                if (to.Date < from.Date || to.Date > DateTime.Now.Date)
                                {
                                    throw new Exception("to date must be equal or greater then from date, and both should be less then today's date");
                                }

                                if (chkBackward.Checked)
                                {
                                    while (from.Date <= to.Date)
                                    {
                                        //For backward compatbility
                                        options["Date"] = from.ToString("yyyyMMdd");
                                        result          = _listner.FormAddToSchedule(service, account, targetDateTime, options, servicePriority);
                                        options.Clear();
                                        if (!result)
                                        {
                                            allSucceed = result;
                                            MessageBox.Show(string.Format("Service {0} for account {1} did not run", service.Name, accountNode.Text));
                                        }
                                        from = from.AddDays(1);
                                    }
                                }
                                else
                                {
                                    DateTimeRange daterange = new DateTimeRange()
                                    {
                                        Start = new DateTimeSpecification()
                                        {
                                            BaseDateTime = from,
                                            Hour         = new DateTimeTransformation()
                                            {
                                                Type = DateTimeTransformationType.Exact, Value = 0
                                            },
                                        },
                                        End = new DateTimeSpecification()
                                        {
                                            BaseDateTime = to,
                                            Hour         = new DateTimeTransformation()
                                            {
                                                Type = DateTimeTransformationType.Max
                                            },
                                        }
                                    };
                                    options.Add(PipelineService.ConfigurationOptionNames.TimePeriod, daterange.ToAbsolute().ToString());
                                    result = _listner.FormAddToSchedule(service, account, targetDateTime, options, servicePriority);
                                    options.Clear();
                                    if (!result)
                                    {
                                        allSucceed = result;
                                        MessageBox.Show(string.Format("Service {0} for account {1} did not run", service.Name, accountNode.Text));
                                    }
                                }
                            }
                            else
                            {
                                result = _listner.FormAddToSchedule(service, account, targetDateTime, options, servicePriority);
                                if (!result)
                                {
                                    allSucceed = result;
                                }
                            }
                        }
                    }
                }
                if (!allSucceed)
                {
                    throw new Exception("Some services did not run");
                }
                else
                {
                    if (countedSelectedServices > 0)
                    {
                        MessageBox.Show(@"Unplaned service\services added successfully");
                    }
                    else
                    {
                        MessageBox.Show(@"No services selected");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 public AccountConfigure(AccountElement element)
 {
     InitializeComponent();
     this.DataContext = new AccountConfigureViewModel(element);
 }
        private void Populate()
        {
            var accountSection = new Section();
            foreach (var account in Application.Accounts)
            {
                var thisAccount = account;
                var t = new AccountElement(thisAccount);
                t.Tapped += () => {
                    AccountSelected(thisAccount);
                };

                //Check to see if this account is the active account. Application.Account could be null
                //so make it the target of the equals, not the source.
                if (thisAccount.Equals(Application.Account))
                    t.Accessory = UITableViewCellAccessory.Checkmark;
                accountSection.Add(t);
            }

            var addAccountSection = new Section();
            var addAccount = new StyledElement("Add Account", () => NavigationController.PushViewController(AddAccount(), true));
            //addAccount.Image = Images.CommentAdd;
            addAccountSection.Add(addAccount);

            Root = new RootElement(Title) { accountSection, addAccountSection };
        }
        public void Init()
        {
            //client.RegisterToServer("*****@*****.**", "David@1&1.de", "David@1&1.de").Wait();

            //Doujin_Interface.Properties.Settings.Default.User = null;

            //-----------------------------------------------------------------------------
            //For Damian
            //On stackoverflow they said the way the task is called migth cause deadlock so it might be a good idea to start looking here
            //-------------------------------------------------------------------------------
            DoujinUtility.MainWindow = this;
            DoujinUtility.MainWindow.animatedBrush.Color = Color.FromArgb(255, 138, 0, 219);
            //var test = new HIDoujin("Bokurano@Mii-chan | Our @Mii-chan","english", 1278968);

            //test2.AddObject("petenshi",Doujin_Interface.UpdateFeed.Types.Arist);
            //(throw new NotImplementedException();

            //Application.Current.Resources["UiDarkGray"] = new SolidColorBrush(Color.FromArgb(100, 200, 20, 20));
            //Color.FromArgb(100, 200, 20, 20);
            this.KeyDown += MainWindow_KeyDown;
            this.KeyUp   += MainWindow_KeyUp;

            var searchElement = new SE();

            search = SE.CreateSearchElement(picgrid, rootGrid, this);
            rootGrid.Children.Add(search);

            registerAndLoginElement = new RegisterElementE();
            rootGrid.Children.Add(registerAndLoginElement);
            registerAndLoginElement.Visibility = Visibility.Hidden;
            accountElement = new AccountElement();
            rootGrid.Children.Add(accountElement);
            accountElement.Visibility = Visibility.Hidden;
            accountElement.Margin     = new Thickness(52, 0, 0, 0);
            rootGrid.Children.Add(notifyer);


            //has to be added last
            var navBar = new NavBar();

            rootGrid.Children.Add(NavBar.CreateNavBar(this));

            Thickness margin = settingElement.Margin;

            margin.Left           = 283;
            settingElement.Margin = margin;
            rootGrid.Children.Add(settingElement);

            if (File.Exists(DatabaseControler.favDataPath))
            {
                DatabaseControler.favorites.ReadXml(DatabaseControler.favDataPath);
                foreach (var row in DatabaseControler.favorites)
                {
                    row.favorite = true;
                    favId.Add(row.nHentaiID);
                    favDoujin.Add(DoujinUtility.DataRowToDoujin(row));
                    Console.WriteLine("fav added to list " + row.nHentaiID);
                }
            }
            if (File.Exists("cache.xml"))
            {
                DatabaseControler.doujinCache.ReadXml("cache.xml");
            }
            //Page(1);
        }
Exemple #23
0
 /// <summary>
 /// 新しいアカウントを追加します。
 /// </summary>
 /// <param name="elem">新しいアカウント要素</param>
 /// <returns>追加できればtrue</returns>
 public static bool RegisterNewAccount(AccountElement elem)
 {
     if (ContainsAccount(elem.CredentialInfo.UserScreenName))
         return false;
     accountModels.Add(elem);
     AccountsChanged();
     return true;
 }
Exemple #24
0
 /// <summary>
 /// ツイートを投稿します。<para />
 /// 同期的に行われます。
 /// </summary>
 /// <param name="accelem">使用するアカウントの列挙</param>
 /// <param name="text">ツイートの本文</param>
 /// <param name="inReplyToId">返信先ID</param>
 public static void UpdateTweet(AccountElement accelem, string text, long? inReplyToId = null)
 {
     Melchior.UpdateTweet(accelem, text, inReplyToId);
 }
Exemple #25
0
        public bool FormAddToSchedule(ActiveServiceElement activeServiceElement, AccountElement account, DateTime targetTime, Edge.Core.SettingsCollection options, ServicePriority servicePriority)
        {
            bool respond = true;

            try
            {
                ServiceConfiguration myServiceConfiguration = new ServiceConfiguration();
                ServiceConfiguration baseConfiguration      = new ServiceConfiguration();
                if (options != null)
                {
                    foreach (string option in options.Keys)
                    {
                        activeServiceElement.Options[option] = options[option];
                    }
                }

                //ServiceElement serviceElement = EdgeServicesConfiguration.Current.Services[activeServiceElement.Name];

                //base configuration;
                baseConfiguration.Name                    = activeServiceElement.Name;
                baseConfiguration.MaxConcurrent           = activeServiceElement.MaxInstances;
                baseConfiguration.MaxCuncurrentPerProfile = activeServiceElement.MaxInstancesPerAccount;


                //configuration per profile
                myServiceConfiguration = new ServiceConfiguration();

                myServiceConfiguration.Name     = activeServiceElement.Name;
                myServiceConfiguration.priority = (int)servicePriority;
                if (activeServiceElement.Options.ContainsKey("ServicePriority"))
                {
                    myServiceConfiguration.priority = int.Parse(activeServiceElement.Options["ServicePriority"]);
                }
                myServiceConfiguration.MaxConcurrent           = (activeServiceElement.MaxInstances == 0) ? 9999 : activeServiceElement.MaxInstances;
                myServiceConfiguration.MaxCuncurrentPerProfile = (activeServiceElement.MaxInstancesPerAccount == 0) ? 9999 : activeServiceElement.MaxInstancesPerAccount;
                myServiceConfiguration.LegacyConfiguration     = activeServiceElement;
                //        //scheduling rules
                myServiceConfiguration.SchedulingRules.Add(new SchedulingRule()
                {
                    Scope             = SchedulingScope.UnPlanned,
                    SpecificDateTime  = targetTime,
                    MaxDeviationAfter = new TimeSpan(0, 0, 45, 0, 0),
                    Hours             = new List <TimeSpan>(),
                    GuidForUnplaned   = Guid.NewGuid()
                });
                myServiceConfiguration.SchedulingRules[0].Hours.Add(new TimeSpan(0, 0, 0, 0));
                myServiceConfiguration.BaseConfiguration = baseConfiguration;
                Edge.Core.Scheduling.Objects.Profile profile = new Edge.Core.Scheduling.Objects.Profile()
                {
                    ID       = account.ID,
                    Name     = account.Name,
                    Settings = new Dictionary <string, object>()
                };
                profile.Settings.Add("AccountID", account.ID.ToString());
                myServiceConfiguration.SchedulingProfile = profile;

                _scheduler.AddNewServiceToSchedule(myServiceConfiguration);
            }
            catch (Exception ex)
            {
                respond = false;
                Edge.Core.Utilities.Log.Write("AddManualServiceListner", ex.Message, ex, Edge.Core.Utilities.LogMessageType.Error);
            }
            return(respond);
        }
 internal void SelectOneUser(AccountElement accountElement)
 {
     TargetElements = new[] { accountElement };
 }
 public TwitterUserViewModel(TwitterUser user, AccountElement parent)
 {
     this.TwitterUser = user;
     this.ParentAccountElement = parent;
 }
Exemple #28
0
        private void addBtn_Click(object sender, EventArgs e)
        {
            ServicePriority servicePriority = ServicePriority.Low;
            var             options         = new Edge.Core.SettingsCollection();
            DateTime        targetDateTime  = new DateTime(dateToRunPicker.Value.Year, dateToRunPicker.Value.Month, dateToRunPicker.Value.Day, timeToRunPicker.Value.Hour, timeToRunPicker.Value.Minute, 0);

            if (priorityCmb.SelectedItem != null)
            {
                switch (priorityCmb.SelectedItem.ToString())
                {
                case "Low":
                {
                    servicePriority = ServicePriority.Low;
                    break;
                }

                case "Normal":
                {
                    servicePriority = ServicePriority.Normal;
                    break;
                }

                case "High":
                {
                    servicePriority = ServicePriority.High;
                    break;
                }

                case "Immediate":
                {
                    servicePriority = ServicePriority.Immediate;
                    break;
                }
                }
            }
            int countedSelectedServices = 0;

            foreach (TreeNode accountNode in servicesTreeView.Nodes)
            {
                foreach (TreeNode serviceNode in accountNode.Nodes)
                {
                    if (!serviceNode.Checked)
                    {
                        continue;
                    }

                    countedSelectedServices++;
                    AccountElement       account = (AccountElement)accountNode.Tag;
                    ActiveServiceElement service = (ActiveServiceElement)serviceNode.Tag;
                    if (useOptionsCheckBox.Checked)
                    {
                        foreach (ListViewItem item in optionsListView.Items)
                        {
                            options.Add(item.SubItems[0].Text.Trim(), item.SubItems[1].Text.Trim());
                        }

                        DateTime from = FromPicker.Value;
                        DateTime to   = toPicker.Value;
                        if (to.Date < from.Date || to.Date > DateTime.Now.Date)
                        {
                            MessageBox.Show(String.Format("Account {0} service {1}: To date must be equal or greater than from date, and both should be less then today's date",
                                                          account.ID,
                                                          service.Name
                                                          ));
                            continue;
                        }

                        DateTimeRange daterange = new DateTimeRange()
                        {
                            Start = new DateTimeSpecification()
                            {
                                BaseDateTime = from,
                                Hour         = new DateTimeTransformation()
                                {
                                    Type = DateTimeTransformationType.Exact, Value = 0
                                },
                            },
                            End = new DateTimeSpecification()
                            {
                                BaseDateTime = to,
                                Hour         = new DateTimeTransformation()
                                {
                                    Type = DateTimeTransformationType.Max
                                },
                            }
                        };
                        options.Add(PipelineService.ConfigurationOptionNames.TimePeriod, daterange.ToAbsolute().ToString());
                    }

                    _listener.AddToSchedule(service, account, targetDateTime, options, servicePriority);
                    options.Clear();
                }
            }

            MessageBox.Show(String.Format("{0} unplanned services were added.", countedSelectedServices));
        }
 public AccountWrap(AccountElement elem)
 {
     this.Element = elem;
     apiUpdateTimer = new Timer(APIUpdate, null, 10000, 5000);
     ViewModelHelper.BindNotifyChanged(elem, this, (o, e) =>
     {
         if (e.PropertyName == "ConnectState")
         {
             RaisePropertyChanged(() => ConnectionState);
             RaisePropertyChanged(() => ConnectionStateString);
         }
         else if (e.PropertyName == "IsUnderControlled")
         {
             RaisePropertyChanged(() => IsPostUnderControlled);
         }
         else if (e.PropertyName == "ReleaseControlTime")
         {
             RaisePropertyChanged(() => ReleaseControlTime);
         }
     });
 }
Exemple #30
0
 public void Add(AccountElement account)
 {
     base.BaseAdd(account);
 }
Exemple #31
0
 /// <summary>
 /// Getting Account Configuration Element from specific configuration
 /// </summary>
 /// <param name="fullPath">Configuration Path ( including file name and extension )</param>
 /// <param name="accountId" >Account ID in the configuration file</param>
 /// <param name="accountElement" >OUT param. The function will return the account element that was found. (NULL if account doesnt exists in this configuration)</param>
 /// <returns>True if found, otherwise:False</returns>
 internal bool TryGetAccountFromExtrernalConfig(string fullPath, int accountId, out AccountElement accountElement)
 {
     try
     {
         EdgeServicesConfiguration.Load(fullPath);
         AccountElementCollection accounts = EdgeServicesConfiguration.Current.Accounts;
         accountElement = accounts.GetAccount(accountId);
         return(true);
     }
     catch
     {
         accountElement = null;
         return(false);
     }
 }
Exemple #32
0
        private void AddUnderControlledAccount(AccountElement elem)
        {
            if (underControlledAccountsDictionary.ContainsKey(elem))
            {
                InformServer.Report("[規制管理: @" + elem.CredentialInfo.UserScreenName + " は規制されています。解除予想時刻: " + underControlledAccountsDictionary[elem].ToString("HH:mm:ss"));
            }
            else
            {

                var timestamp = DateTime.Now.Subtract(Setting.Instance.TwitterProperty.UnderControlTimespan);

                // APIを利用してツイートを遡り受信
                InformServer.Report("[規制管理: @" + elem.CredentialInfo.UserScreenName + " の直近のツイートを受信しています...]", InformServer.NotifyLevel.Note);

                var recvs = Executive.ExecApi(() => elem.CredentialInfo.GetUserTimeline(count: 200, include_rts: true));
                if (recvs != null)
                    Registrant.RegisterStatusBases(recvs, elem);

                // 127tweet/3hours
                var originate = TweetModel.GetAllTweets(
                    (t) => t.User.ScreenName == elem.CredentialInfo.UserScreenName)
                    .OrderByDescending((t) => t.CreatedAt)
                    .Skip(Setting.Instance.TwitterProperty.UnderControlCount - 1)
                    .FirstOrDefault();

                if (originate == null)
                {
                    InformServer.Report("[規制管理: @" + elem.CredentialInfo.UserScreenName + " はPOST規制されていますが、解除時刻を予想できません。しばらく置いて試してみてください。]", InformServer.NotifyLevel.Note);
                }
                else
                {
                    var release = (originate.CreatedAt + Setting.Instance.TwitterProperty.UnderControlTimespan);
                    InformServer.Report("[規制管理: @" + elem.CredentialInfo.UserScreenName +
                        " はPOST規制されています。解除予想時刻は " + release.ToString("HH:mm:ss") + " です。]");
                    underControlledAccountsDictionary.Add(elem, release);
                    ChangeUnderControlledAccounts(elem, true);
                }
            }
        }
Exemple #33
0
        internal void UpdateTweet(AccountElement accelem, string text, long? inReplyToId = null)
        {
            if (Setting.Instance.InputExperienceProperty.TrimBeginSpace)
            {
                text = text.TrimStart(' ', '\t', ' ');
            }
            try
            {
                var status = accelem.CredentialInfo.UpdateStatus(text, inReplyToId);
                Registrant.RegisterStatusBase(status, accelem);
                InformServer.Report("ツイートしました:@" + accelem.CredentialInfo.UserScreenName + ": " + text, InformServer.NotifyLevel.Note);

                var timestamp = DateTime.Now.Subtract(Setting.Instance.TwitterProperty.UnderControlTimespan);
                // 過去3時間以内のツイート数を取得
                var rcnt = TweetModel.GetAllTweets(
                    (t) => t.User.ScreenName == accelem.CredentialInfo.UserScreenName &&
                           timestamp < t.CreatedAt).Count();
                if (rcnt >= Setting.Instance.TwitterProperty.UnderControlWarningThreshold)
                {
                    // 規制から明けたばかりかもしれない
                    var times = TweetModel.GetAllTweets(
                        (t) => t.User.ScreenName == accelem.CredentialInfo.UserScreenName)
                        .Select(t => t.CreatedAt)
                        .Take(Setting.Instance.TwitterProperty.UnderControlCount * 2) // 直近2枠分を持ってこれば良い
                        .ToArray();

                    // 規制がスタートされたポイントは、[i+127-1]が3h以内のとき
                    int i = 0;
                    bool controlPointFound = false;
                    for (i = 0; i + Setting.Instance.TwitterProperty.UnderControlCount < times.Length && i < Setting.Instance.TwitterProperty.UnderControlCount; i++)
                    {
                        if (times[i] - times[i + Setting.Instance.TwitterProperty.UnderControlCount - 1] < Setting.Instance.TwitterProperty.UnderControlTimespan)
                        {
                            // 時間内に規制を行われる以上の投稿を行っている
                            controlPointFound = true;
                            break;
                        }
                    }

                    if (controlPointFound)
                    {
                        // 規制スタートポイントが判明した
                        if(i >= Setting.Instance.TwitterProperty.UnderControlWarningThreshold)
                            throw new TweetAnnotationException(TweetAnnotationException.AnnotationKind.NearUnderControl);
                    }
                    else
                    {
                        // そろそろ規制されるんじゃない?
                        throw new TweetAnnotationException(TweetAnnotationException.AnnotationKind.NearUnderControl);
                    }
                }
            }
            catch (WebException wex)
            {
                if (wex.Status == WebExceptionStatus.ProtocolError)
                {
                    var hrw = wex.Response as HttpWebResponse;
                    if (hrw != null)
                    {

                        if (hrw.StatusCode == HttpStatusCode.Forbidden)
                        {
                            // 規制?
                            using (var strm = hrw.GetResponseStream())
                            {
                                var xdoc = XDocument.Load(strm);
                                var eel = xdoc.Root.Element("error");
                                if (eel != null)
                                {
                                    if (eel.Value.IndexOf("update limit", StringComparison.CurrentCultureIgnoreCase) >= 0)
                                    {
                                        // User is over daily status update limit.
                                        // POST規制
                                        AddUnderControlledAccount(accelem);
                                        throw new TweetFailedException(TweetFailedException.TweetErrorKind.Controlled);
                                    }
                                    else if (eel.Value.IndexOf("duplicate", StringComparison.CurrentCultureIgnoreCase) >= 0)
                                    {
                                        // 同じツイートをしようとした
                                        throw new TweetFailedException(TweetFailedException.TweetErrorKind.Duplicated);
                                    }
                                    else
                                    {
                                        // 何かよくわからない
                                        throw new TweetFailedException(TweetFailedException.TweetErrorKind.CommonFailed, eel.Value);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (wex.Status == WebExceptionStatus.Timeout)
                    {
                        // タイムアウト
                        throw new TweetFailedException(TweetFailedException.TweetErrorKind.Timeout, "ツイートに失敗しました(タイムアウトしました。Twitterが不調かも)", wex);
                    }
                    else
                    {
                        // 何かがおかしい
                        throw new TweetFailedException(TweetFailedException.TweetErrorKind.CommonFailed, "ツイートに失敗しました(" + (int)wex.Status + ")", wex);
                    }
                }
            }
            catch (TweetAnnotationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new TweetFailedException(TweetFailedException.TweetErrorKind.CommonFailed, "ツイートに失敗しました(" + ex.Message + ")", ex);
            }
        }
Exemple #34
0
 /// <summary>
 /// ツイートを消し去ります。(非同期)<para />
 /// TweetModelからも消し去ります。
 /// </summary>
 /// <param name="accelem">つぶやいたアカウント</param>
 /// <param name="tweetId">ツイートのID</param>
 public static void RemoveTweet(AccountElement accelem, long tweetId)
 {
     Melchior.RemoveTweet(accelem, tweetId);
 }
Exemple #35
0
 internal void RemoveTweet(AccountElement descriptor, long tweetId)
 {
     Task.Factory.StartNew(() => RemoveTweetSink(descriptor, tweetId), TaskCreationOptions.LongRunning);
 }
Exemple #36
0
        /// <summary>
        /// クレデンシャル情報を書き換えます。
        /// </summary>
        /// <param name="elem">新しいクレデンシャル情報を含むアカウント</param>
        /// <returns>更新に成功したらtrue</returns>
        public static bool UpdateAccount(AccountElement elem)
        {
            var olde = GetAccountElement(elem.CredentialInfo.UserScreenName);

            if (olde == null)
                return false;

            // クレデンシャル情報の書き換え
            olde.CredentialInfo = elem.CredentialInfo;
            AccountsChanged();
            return true;

        }
Exemple #37
0
 private void RemoveTweetSink(AccountElement descriptor, long tweetId)
 {
     var tweet = Executive.ExecApi(() => descriptor.CredentialInfo.DestroyStatus(tweetId));
     if (tweet != null)
     {
         if (tweet.Id != tweetId)
         {
             InformServer.Report("削除には成功しましたが、ツイートIDが一致しません。(" + tweetId.ToString() + " -> " + tweet.Id.ToString() + ")");
         }
         else
         {
             TweetModel.Remove(tweetId);
             InformServer.Report("削除しました:" + tweet.ToString(), InformServer.NotifyLevel.Note);
         }
     }
     else
     {
         InformServer.Report("ツイートを削除できませんでした(@" + descriptor.CredentialInfo.UserScreenName + ")", InformServer.NotifyLevel.Error);
     }
 }
 public AccountConfigureViewModel(AccountElement elem)
 {
     Element = elem;
 }
 public UserLinkData(UserSelectorViewModel parentVm, AccountElement element, bool linking)
 {
     this.ParentVM = parentVm;
     Element = element;
     Link = linking;
 }
Exemple #40
0
 internal ReceiveSlave(ITwitterStreaming strm, AccountElement elem)
 {
     stream = strm;
     strm.OnDisconnected += new Action<bool>(strm_OnDisconnected);
     acElem = elem;
 }
Exemple #41
0
 internal ReceiveInterface(AccountElement element)
 {
     UseAccount = element;
     core = new Interior.ReceiveCore(element);
     core.StateChanged += new Action(core_StateChanged);
 }
 public AccountElementViewModel(AccountElement wrap)
 {
     if(wrap == null)
         throw new ArgumentNullException("wrap");
     this.AccountElement = wrap;
 }
Exemple #43
0
        public bool AddToSchedule(string serviceName, int accountID, DateTime targetTime, SettingsCollection options)
        {
            // YANIV:
            // if cannot perform at requested time, or can only perform after max deviation expires -
            // throw exception with a message

            ActiveServiceElement startupElement = null;

            if (accountID < 0)
            {
                AccountServiceElement elem = ServicesConfiguration.SystemAccount.Services[serviceName];
                if (elem != null)
                {
                    startupElement = new ActiveServiceElement(elem);
                }
                else
                {
                    startupElement = new ActiveServiceElement(ServicesConfiguration.Services[serviceName]);
                }
            }
            else
            {
                AccountElement account = ServicesConfiguration.Accounts.GetAccount(accountID);
                if (account == null)
                {
                    // EXCEPTION:
                    return(false);
                    //throw new ArgumentException(
                    //    String.Format("Account with ID {0} does not exist.", accountID),
                    //    "accountID");
                }

                AccountServiceElement accountService = account.Services[serviceName];
                if (accountService == null)
                {
                    // EXCEPTION
                    // throw new ArgumentException(String.Format("Service {0} is not defined for account {1}", serviceName, account.Name), "serviceName");
                    return(false);
                    // Log.Write(String.Format("Service {0} is not defined for account {1}", serviceName, account.Name), LogMessageType.Warning);
                }
                else
                {
                    startupElement = new ActiveServiceElement(accountService);
                }
            }


            // Couldn't find exception
            if (startupElement == null)
            {
                // EXCEPTION:
                return(false);
                //throw new ArgumentException(
                //    String.Format("The requested service \"{0}\" could not be found.", serviceName),
                //    "serviceName");
            }

            // Merge the options
            if (options != null)
            {
                foreach (KeyValuePair <string, string> pair in options)
                {
                    startupElement.Options[pair.Key] = pair.Value;
                }
            }

            // Add the manual request.
            if (targetTime < DateTime.Now)
            {
                _builder.AddManualRequest(startupElement, accountID);
            }
            else
            {
                _builder.AddManualRequest(startupElement, targetTime, accountID);
            }

            return(true);
        }
 public Relation(AccountElement elem, TwitterUser user)
 {
     this.Element = elem;
     this.TargetUser = user;
     IsInactive = false;
     RefreshUserData();
     if (Math.Abs(elem.Following.Count - elem.TwitterUserData.FriendsCount) > 10)
         IsDataOutOfDate = true;
 }
Exemple #45
0
        public HttpResponseMessage Index()
        {
            using (var Context = new DatabaseContext())
            {
                XDocument  Doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/SAFT.xml"));
                XNamespace ns  = Doc.Root.GetDefaultNamespace();

                AuditFile AuditFile = new AuditFile();

                #region Header

                XElement HeaderElement = Doc.Root.Element(ns + "Header");
                AuditFile.CompanyID  = int.Parse(HeaderElement.Element(ns + "CompanyID").Value);
                AuditFile.FiscalYear = int.Parse(HeaderElement.Element(ns + "FiscalYear").Value);
                AuditFile.Header     = new Header
                {
                    AuditFileVersion      = HeaderElement.Element(ns + "AuditFileVersion").Value,
                    CompanyID             = int.Parse(HeaderElement.Element(ns + "CompanyID").Value),
                    TaxRegistrationNumber = int.Parse(HeaderElement.Element(ns + "TaxRegistrationNumber").Value),
                    TaxAccountingBasis    = HeaderElement.Element(ns + "TaxAccountingBasis").Value,
                    CompanyName           = HeaderElement.Element(ns + "CompanyName").Value,
                    FiscalYear            = int.Parse(HeaderElement.Element(ns + "FiscalYear").Value),
                    StartDate             = DateTime.Parse(HeaderElement.Element(ns + "StartDate").Value),
                    EndDate                   = DateTime.Parse(HeaderElement.Element(ns + "EndDate").Value),
                    CurrencyCode              = HeaderElement.Element(ns + "CurrencyCode").Value,
                    DateCreated               = DateTime.Parse(HeaderElement.Element(ns + "DateCreated").Value),
                    TaxEntity                 = HeaderElement.Element(ns + "TaxEntity").Value,
                    ProductCompanyTaxID       = int.Parse(HeaderElement.Element(ns + "ProductCompanyTaxID").Value),
                    SoftwareCertificateNumber = HeaderElement.Element(ns + "SoftwareCertificateNumber").Value,
                    ProductID                 = HeaderElement.Element(ns + "ProductID").Value,
                    ProductVersion            = HeaderElement.Element(ns + "ProductVersion").Value,
                };

                XElement CompanyAddressElement = HeaderElement.Element(ns + "CompanyAddress");
                AuditFile.Header.CompanyAddress = new CompanyAddress
                {
                    StreetName    = CompanyAddressElement.Element(ns + "StreetName").Value,
                    AddressDetail = CompanyAddressElement.Element(ns + "AddressDetail").Value,
                    City          = CompanyAddressElement.Element(ns + "City").Value,
                    Country       = CompanyAddressElement.Element(ns + "Country").Value,
                    PostalCode    = CompanyAddressElement.Element(ns + "PostalCode").Value,
                    Region        = CompanyAddressElement.Element(ns + "Region").Value,
                };

                if (Context.AuditFile.Any(e => e.Header.CompanyID == AuditFile.Header.CompanyID && e.Header.FiscalYear == AuditFile.Header.FiscalYear))
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, "Audit file already exists."));
                }

                #endregion

                #region SourceDocuments

                XElement SourceDocumentsElement = Doc.Root.Element(ns + "SourceDocuments");
                AuditFile.SourceDocuments = new SourceDocuments
                {
                    SalesInvoices = new SalesInvoices(),
                };

                XElement SalesInvoicesElement = SourceDocumentsElement.Element(ns + "SalesInvoices");
                AuditFile.SourceDocuments.SalesInvoices = new SalesInvoices
                {
                    NumberOfEntries = int.Parse(SalesInvoicesElement.Element(ns + "NumberOfEntries").Value),
                    TotalDebit      = float.Parse(SalesInvoicesElement.Element(ns + "TotalDebit").Value),
                    TotalCredit     = float.Parse(SalesInvoicesElement.Element(ns + "TotalCredit").Value),
                    Invoices        = new List <Invoice>(),
                };

                IEnumerable <XElement> InvoicesElements = SalesInvoicesElement.Elements(ns + "Invoice");
                foreach (var InvoiceElement in InvoicesElements)
                {
                    Invoice Invoice = new Invoice
                    {
                        InvoiceNo         = InvoiceElement.Element(ns + "InvoiceNo").Value,
                        ATCUD             = InvoiceElement.Element(ns + "ATCUD").Value,
                        Hash              = InvoiceElement.Element(ns + "Hash").Value,
                        HashControl       = int.Parse(InvoiceElement.Element(ns + "HashControl").Value),
                        Period            = InvoiceElement.Element(ns + "Period").Value,
                        InvoiceDate       = DateTime.Parse(InvoiceElement.Element(ns + "InvoiceDate").Value),
                        InvoiceType       = InvoiceElement.Element(ns + "InvoiceType").Value,
                        SourceID          = InvoiceElement.Element(ns + "SourceID").Value,
                        SystemEntryDate   = DateTime.Parse(InvoiceElement.Element(ns + "SystemEntryDate").Value),
                        CustomerID        = InvoiceElement.Element(ns + "CustomerID").Value,
                        MovementStartTime = DateTime.Parse(InvoiceElement.Element(ns + "MovementStartTime").Value),
                        Lines             = new List <InvoiceLine>(),
                    };

                    XElement DocumentStatusElement = InvoiceElement.Element(ns + "DocumentStatus");
                    Invoice.DocumentStatus = new DocumentStatus
                    {
                        InvoiceStatus     = DocumentStatusElement.Element(ns + "InvoiceStatus").Value,
                        InvoiceStatusDate = DateTime.Parse(DocumentStatusElement.Element(ns + "InvoiceStatusDate").Value),
                        SourceID          = DocumentStatusElement.Element(ns + "SourceID").Value,
                        SourceBilling     = DocumentStatusElement.Element(ns + "SourceBilling").Value,
                    };

                    XElement SpecialRegimesElement = InvoiceElement.Element(ns + "SpecialRegimes");
                    Invoice.SpecialRegimes = new SpecialRegimes
                    {
                        SelfBillingIndicator         = int.Parse(SpecialRegimesElement.Element(ns + "SelfBillingIndicator").Value),
                        CashVATSchemeIndicator       = int.Parse(SpecialRegimesElement.Element(ns + "CashVATSchemeIndicator").Value),
                        ThirdPartiesBillingIndicator = int.Parse(SpecialRegimesElement.Element(ns + "ThirdPartiesBillingIndicator").Value),
                    };

                    XElement ShipToElement = InvoiceElement.Element(ns + "ShipTo");
                    Invoice.ShipTo = new ShipTo
                    {
                        DeliveryDate = DateTime.Parse(ShipToElement.Element(ns + "DeliveryDate").Value),
                    };
                    XElement ShipToAddressElement = ShipToElement.Element(ns + "Address");
                    Invoice.ShipTo.Address = new Address
                    {
                        AddressDetail = ShipToAddressElement.Element(ns + "AddressDetail").Value,
                        City          = ShipToAddressElement.Element(ns + "City").Value,
                        PostalCode    = ShipToAddressElement.Element(ns + "PostalCode").Value,
                        Country       = ShipToAddressElement.Element(ns + "Country").Value,
                    };

                    XElement ShipFromElement = InvoiceElement.Element(ns + "ShipFrom");
                    Invoice.ShipFrom = new ShipFrom
                    {
                        DeliveryDate = DateTime.Parse(ShipFromElement.Element(ns + "DeliveryDate").Value),
                    };
                    XElement ShipFromAddressElement = ShipFromElement.Element(ns + "Address");
                    Invoice.ShipFrom.Address = new Address
                    {
                        AddressDetail = ShipFromAddressElement.Element(ns + "AddressDetail").Value,
                        City          = ShipFromAddressElement.Element(ns + "City").Value,
                        PostalCode    = ShipFromAddressElement.Element(ns + "PostalCode").Value,
                        Country       = ShipFromAddressElement.Element(ns + "Country").Value,
                    };

                    XElement DocumentTotalsElement = InvoiceElement.Element(ns + "DocumentTotals");
                    Invoice.DocumentTotals = new DocumentTotals
                    {
                        GrossTotal = float.Parse(DocumentTotalsElement.Element(ns + "GrossTotal").Value),
                        NetTotal   = float.Parse(DocumentTotalsElement.Element(ns + "NetTotal").Value),
                        TaxPayable = float.Parse(DocumentTotalsElement.Element(ns + "TaxPayable").Value),
                    };

                    XElement WithholdingTaxElement = InvoiceElement.Element(ns + "WithholdingTax");
                    Invoice.WithholdingTax = new WithholdingTax
                    {
                        WithholdingTaxAmount = float.Parse(WithholdingTaxElement.Element(ns + "WithholdingTaxAmount").Value),
                    };

                    IEnumerable <XElement> LineElements = InvoiceElement.Elements(ns + "Line");
                    foreach (var LineElement in LineElements)
                    {
                        InvoiceLine Line = new InvoiceLine
                        {
                            LineNumber         = int.Parse(LineElement.Element(ns + "LineNumber").Value),
                            ProductCode        = LineElement.Element(ns + "ProductCode").Value,
                            ProductDescription = LineElement.Element(ns + "ProductDescription").Value,
                            Quantity           = int.Parse(LineElement.Element(ns + "Quantity").Value),
                            UnitOfMeasure      = LineElement.Element(ns + "UnitOfMeasure").Value,
                            UnitPrice          = float.Parse(LineElement.Element(ns + "UnitPrice").Value),
                            TaxPointDate       = DateTime.Parse(LineElement.Element(ns + "TaxPointDate").Value),
                            Description        = LineElement.Element(ns + "Description").Value,
                            CreditAmount       = float.Parse(LineElement.Element(ns + "CreditAmount").Value),
                            SettlementAmount   = float.Parse(LineElement.Element(ns + "SettlementAmount").Value),
                        };

                        XElement TaxElement = LineElement.Element(ns + "Tax");
                        Line.Tax = new Tax
                        {
                            TaxCode          = TaxElement.Element(ns + "TaxCode").Value,
                            TaxCountryRegion = TaxElement.Element(ns + "TaxCountryRegion").Value,
                            TaxPercentage    = float.Parse(TaxElement.Element(ns + "TaxPercentage").Value),
                            TaxType          = TaxElement.Element(ns + "TaxType").Value,
                        };

                        Invoice.Lines.Add(Line);
                    }

                    AuditFile.SourceDocuments.SalesInvoices.Invoices.Add(Invoice);
                }

                #endregion

                #region MasterFiles

                XElement MasterFilesElement = Doc.Root.Element(ns + "MasterFiles");
                AuditFile.MasterFiles = new MasterFiles
                {
                    Customers             = new List <Customer>(),
                    GeneralLedgerAccounts = new GeneralLedgerAccounts(),
                };

                XElement GeneralLedgerAccountsElement = MasterFilesElement.Element(ns + "GeneralLedgerAccounts");
                AuditFile.MasterFiles.GeneralLedgerAccounts = new GeneralLedgerAccounts
                {
                    Accounts = new List <Account>(),
                };
                IEnumerable <XElement> AccountElements = GeneralLedgerAccountsElement.Elements(ns + "Account");
                foreach (var AccountElement in AccountElements)
                {
                    Account Account = new Account
                    {
                        AccountID            = long.Parse(AccountElement.Element(ns + "AccountID").Value),
                        AccountDescription   = AccountElement.Element(ns + "AccountDescription").Value,
                        OpeningDebitBalance  = float.Parse(AccountElement.Element(ns + "OpeningDebitBalance").Value),
                        OpeningCreditBalance = float.Parse(AccountElement.Element(ns + "OpeningCreditBalance").Value),
                        ClosingDebitBalance  = float.Parse(AccountElement.Element(ns + "ClosingDebitBalance").Value),
                        ClosingCreditBalance = float.Parse(AccountElement.Element(ns + "ClosingCreditBalance").Value),
                        GroupingCategory     = AccountElement.Element(ns + "GroupingCategory").Value,
                    };

                    AuditFile.MasterFiles.GeneralLedgerAccounts.Accounts.Add(Account);
                }

                IEnumerable <XElement> CustomerElements = MasterFilesElement.Elements(ns + "Customer");
                foreach (var CustomerElement in CustomerElements)
                {
                    Customer Customer = new Customer
                    {
                        AccountID            = CustomerElement.Element(ns + "AccountID").Value,
                        CompanyName          = CustomerElement.Element(ns + "CompanyName").Value,
                        CustomerID           = CustomerElement.Element(ns + "CustomerID").Value,
                        CustomerTaxID        = CustomerElement.Element(ns + "CustomerTaxID").Value,
                        SelfBillingIndicator = CustomerElement.Element(ns + "SelfBillingIndicator").Value,
                    };

                    XElement BillingAddressElement = CustomerElement.Element(ns + "BillingAddress");
                    Customer.BillingAddress = new Address
                    {
                        AddressDetail = BillingAddressElement.Element(ns + "AddressDetail").Value,
                        City          = BillingAddressElement.Element(ns + "City").Value,
                        Country       = BillingAddressElement.Element(ns + "Country").Value,
                        PostalCode    = BillingAddressElement.Element(ns + "PostalCode").Value,
                    };

                    XElement ShipToAddressElement = CustomerElement.Element(ns + "ShipToAddress");
                    Customer.ShipToAddress = new Address
                    {
                        AddressDetail = ShipToAddressElement.Element(ns + "AddressDetail").Value,
                        City          = ShipToAddressElement.Element(ns + "City").Value,
                        Country       = ShipToAddressElement.Element(ns + "Country").Value,
                        PostalCode    = ShipToAddressElement.Element(ns + "PostalCode").Value,
                    };

                    AuditFile.MasterFiles.Customers.Add(Customer);
                }

                #endregion

                Context.AuditFile.Add(AuditFile);
                Context.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.Created, "Created audit file."));
            }
        }