Наследование: IProfile
Пример #1
0
 static void UpdateModelInfo(dynamic model)
 {
     var modelType = model.GetType();
     var profile = new Profile(); 
     profile.Address1 = model.Address1;
     profile.Telephone = model.Telephone;
 }
Пример #2
0
        public void TestAuthenticateInsecureLoginDisallowed()
        {
            using (var server = new PopPseudoServer()) {
            server.Start();

            var prof = new Profile(new NetworkCredential("user", "pass"), "user;auth=*", server.HostPort);

            prof.UsingSaslMechanisms = new[] {"LOGIN", "PLAIN", "ANONYMOUS", "CRAM-MD5"};
            prof.AllowInsecureLogin = false;

            // greeting
            server.EnqueueResponse("+OK <timestamp@localhost>\r\n");
            // CAPA response
            server.EnqueueResponse("+OK\r\n" +
                               "SASL X-UNKNOWN DIGEST-MD5 CRAM-MD5 NTLM PLAIN LOGIN ANONYMOUS\r\n" +
                               ".\r\n");
            // AUTH CRAM-MD5 response
            server.EnqueueResponse("+ PDQwMDEzNDQxMTIxNDM1OTQuMTI3MjQ5OTU1MEBsb2NhbGhvc3Q+\r\n");
            server.EnqueueResponse("+OK\r\n");

            using (var session = PopSessionCreator.CreateSession(prof, null, null)) {
              Assert.AreEqual(PopSessionState.Transaction, session.State);
              Assert.AreEqual(prof.Authority, session.Authority);
            }

            server.DequeueRequest(); // CAPA
            StringAssert.Contains("AUTH CRAM-MD5", server.DequeueRequest());
              }
        }
Пример #3
0
    public void SynchronizeProfile(Profile profile)
    {
        if (profile == null)
        {
            throw new ArgumentNullException("profile");
        }

        if (profile.ID < 0)
        {
            // It is a local profile.
            if (profile.IsSynchronizable)
            {
                NetworkManager.Instance.IsProfileExist(profile, this.CreateProfileDelegate);
            }
            else
            {
                // It is a local profile only, try to create a new profile from the data of the current one.
                this.CreateProfileDelegate(profile, false);
            }
        }
        else
        {
            // It is an already validate profile.
            NetworkManager.Instance.SynchronizeProfile(profile);
        }
    }
Пример #4
0
        public void Populate() {
            var Profile1 = new Profile {
                Title = "Main Profile",
                };
            Profile1.Fingerprint.Value = "blahhhh";

            Selector.Add(Profile1);

            var Profile2 = new Profile {
                Title = "Site Profile"
                };
            Profile2.Fingerprint.Value = "More blahdy blah";
            Selector.Add(Profile2);


            Profile1.Devices.Value = new List<Goedel.Trojan.Object>();
            var Device1 = new Device {
                Title = "Voodoo" };
            Profile1.Devices.Value.Add(Device1);

            var Device2 = new Device {
                Title = "iPad" };
            Profile1.Devices.Value.Add(Device2);

            var Device3 = new Device {
                Title = "Router" };
            Profile1.Devices.Value.Add(Device3);


            }
Пример #5
0
        public void TestAuthenticateAnonymousMechanismSpecified()
        {
            using (var server = new PopPseudoServer()) {
            server.Start();

            var prof = new Profile(null, "user%40pop.example.net;auth=anonymous", server.HostPort);

            // greeting
            server.EnqueueResponse("+OK\r\n");
            // CAPA response
            server.EnqueueResponse("+OK\r\n" +
                               "SASL ANONYMOUS\r\n" +
                               ".\r\n");
            // AUTH response
            server.EnqueueResponse("+OK\r\n");

            using (var session = PopSessionCreator.CreateSession(prof, null, null)) {
              Assert.AreEqual(PopSessionState.Transaction, session.State);
              Assert.AreEqual(prof.Authority, session.Authority);
            }

            server.DequeueRequest(); // CAPA
            StringAssert.StartsWith("AUTH ANONYMOUS dXNlckBwb3AuZXhhbXBsZS5uZXQ=", server.DequeueRequest());
              }
        }
Пример #6
0
        public void TestAuthenticateAnonymousMechanismSpecifiedAuthenticationFailure()
        {
            using (var server = new PopPseudoServer()) {
            server.Start();

            var prof = new Profile(null, "user%40pop.example.net;auth=anonymous", server.HostPort);

            // greeting
            server.EnqueueResponse("+OK\r\n");
            // CAPA response
            server.EnqueueResponse("+OK\r\n" +
                               "SASL ANONYMOUS\r\n" +
                               ".\r\n");
            // AUTH response
            server.EnqueueResponse("-ERR\r\n");

            try {
              Assert.IsNull(PopSessionCreator.CreateSession(prof, null, null));
              Assert.Fail("PopAuthenticationException not thrown");
            }
            catch (PopAuthenticationException ex) {
              Assert.IsNull(ex.InnerException);
              Assert.IsNotNull(ex.Result);
              Assert.AreEqual(Protocol.Client.PopCommandResultCode.Error, ex.Result.Code);
            }

            server.DequeueRequest(); // CAPA
            StringAssert.StartsWith("AUTH ANONYMOUS dXNlckBwb3AuZXhhbXBsZS5uZXQ=", server.DequeueRequest());
              }
        }
Пример #7
0
        public void RegisterUser(JsonObject ps)
        {
            Profile p = new Profile();

            ProfileManager pm = new ProfileManager();

            FacebookService fb = new FacebookService();
            Facebook.JsonObject o = fb.DownloadData<Facebook.JsonObject>("/me", ps["accessToken"].ToString());

            if (pm.LoadUser(o["email"].ToString()) != null)
                throw new Exception("Profile already exists");

            p.CreationDate = DateTime.Now;
            p.Email = o["email"].ToString();
            p.IsLockedOut = false;

            if (o.ContainsKey("username"))
                p.UserName = o["username"].ToString();
            else
                p.UserName = ps["userID"].ToString();

            pm.RegisterUser(p);

            SocialConnection sc = new SocialConnection();
            sc.OauthToken = ps["accessToken"].ToString();
            sc.ReferenceID = ps["userID"].ToString();
            sc.ServiceID = SocialServiceType.Facebook;
            sc.UserID = p.UserID;

            SocialServiceManager scm = new SocialServiceManager();
            scm.AddConnection(sc);

            pm.ReleaseAuthenticationTicket(p);
        }
Пример #8
0
        public static Profile LoadProfile(string ProfileFilePath)
        {
            Helper_FileEncoding.CheckFileEncodingAndChange(ProfileFilePath, Setting_Global.DefaultIniFileEncoding);

            string ProfileName = Path.GetFileName(ProfileFilePath);
            string[] ButtonsName = Helper_INIFile.IniGetAllSections(ProfileFilePath);

            if (ButtonsName.Length > 0)
            {
                Profile.Button[] ProfileButtons = new Profile.Button[ButtonsName.Length];

                for (int i = 0; i < ButtonsName.Length; i++)
                {
                    string ButtonName = ButtonsName[i];
                    string KeyQuery = Helper_INIFile.IniReadValue(ButtonsName[i], "KeyQuery", ProfileFilePath);
                    int Repeat = Convert.ToInt32(Helper_INIFile.IniReadValue(ButtonsName[i], "Repeat", ProfileFilePath));
                    Profile.Button.TimeInterval RepeatInterval = new Profile.Button.TimeInterval(Helper_INIFile.IniReadValue(ButtonsName[i], "RepeatInterval", ProfileFilePath));
                    Profile.Button ProfileButton = new Profile.Button(ButtonName, KeyQuery, Repeat, RepeatInterval);
                    ProfileButtons[i] = ProfileButton;
                }

                Profile Profile = new Profile(ProfileName, ProfileButtons);

                return Profile;
            }
            else
            {
                return null;
            }
        }
Пример #9
0
    public void Open(string fn)
    {
        Profile p = new Profile (fn);
        p.ReadMetadata ();

        Add (new TypeGraphComponent (p));
    }
Пример #10
0
        public void SetUp()
        {
            var validatorMock = new Mock<IValidator>();
            validatorMock.Setup(v => v.TryValidate(It.IsAny<Profile>()))
                .Returns(true);

            var repoMock = new Mock<IRepository<Profile, int>>();
            repoMock.Setup(m => m.Add(It.IsAny<Profile>()))
                .Returns(new Profile
                                    {
                                        Id = 65,
                                        FirstName = "Joe",
                                        LastName = "Smith",
                                        EmailAddress = "*****@*****.**"
                                    });

            _interactor = new AddProfileInteractor(repoMock.Object, validatorMock.Object)
            {
                FirstName = "Joe",
                LastName = "Smith",
                EmailAddress = "*****@*****.**"
            };

            _result = _interactor.Execute();
        }
Пример #11
0
 public void ShouldBeAbleToCreateUserWithProfile()
 {
     var loginid = new LoginId("*****@*****.**");
     var name = new Name("firstName", "lastName");
     var profile = new Profile("Some useful profile goes here");
     new User(loginid, name) {Profile = profile};
 }
        public async Task<IHttpActionResult> PutProfile(int id, Profile profile)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != profile.ProfileID)
            {
                return BadRequest();
            }

            db.Entry(profile).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProfileExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
Пример #13
0
    public void LoadProfiles_SettingsIsEmpty_ShouldReturnExistentProfilesEnumerable([Content] Item item, CurrentInteraction currentInteraction, ITracker tracker, Profile profile)
    {
      var profileSettingItem = item.Add("profileSetting", new TemplateID(Templates.ProfilingSettings.ID));
      var profileItem = item.Add("profile", new TemplateID(ProfileItem.TemplateID));


      var provider = new ProfileProvider();

      var fakeSiteContext = new FakeSiteContext(new StringDictionary
      {
        {
          "rootPath", "/sitecore"
        },
        {
          "startItem", profileSettingItem.Paths.FullPath.Remove(0, "/sitecore".Length)
        }
      });

      fakeSiteContext.Database = item.Database;

      using (new SiteContextSwitcher(fakeSiteContext))
      {
        provider.GetSiteProfiles().Count().Should().Be(0);
      }
    }
Пример #14
0
        protected override void BeginProcessing()
        {
            Profile profile = new Profile(Name);
            
            Profile checkProfile = 
                CurrentData.GetProfile(profile.Name);
            
            if (checkProfile == null) {
                CurrentData.Profiles.Add(profile);
                WriteObject(this, profile);
            } else {
                // 20130323
//                ErrorRecord err = 
//                    new ErrorRecord(
//                        new Exception("The profile already exists"),
//                        "ProfileAlreadyExists",
//                        ErrorCategory.InvalidArgument,
//                        profile);
//                err.ErrorDetails = 
//                    new ErrorDetails("The profile already exists");
//                WriteError(this, err, true);
                
                WriteError(
                    this,
                    "The profile already exists",
                    "ProfileAlreadyExists",
                    ErrorCategory.InvalidArgument,
                    true);
            }
        }
Пример #15
0
        // Create new profile using Entity Framework and save the changes to the database
        private void AddProfileToDatabase(String name)
        {
            if (textBoxName.Text.Length == 0)
            {
                MessageBox.Show(@"Please enter a name");
                return;
            }

            if (textBoxName.Text.Length > 20)
            {
                MessageBox.Show(@"There is a limit of 20 characters" + Environment.NewLine +
                                @"You entered " + textBoxName.Text.Length + @" characters");
                return;
            }

            using (var db = new HighscoresEntities())
            {
                var profile = new Profile {ProfileName = name};

                db.Profiles.Add(profile);
                db.SaveChanges();
            }

            textBoxName.Clear();
            CollapseForm();
        }
 public User BuildRegister(AccountRegisterViewModel viewModel)
 {
     if (viewModel == null)
     {
         throw new ArgumentNullException("viewModel");
     }
     if (!viewModel.Password.Equals(viewModel.PasswordConfirmation))
     {
         throw new ArgumentException("The passwords are not equal.");
     }
     var resultUser = new User(viewModel.Email);
     var resultProfile = new Profile(resultUser);
     resultUser.UserProfile = resultProfile;
     resultProfile.FirstName = viewModel.FirstName;
     resultProfile.LastName = viewModel.LastName;
     resultProfile.RegistrationDate = DateTime.UtcNow;
     resultProfile.LastSignIn = DateTime.UtcNow;
     resultProfile.LastSignOut = DateTime.UtcNow;
     resultProfile.IsSignedIn = true;
     resultUser.PasswordSalt =
         this._hashGenerator.GenerateSalt(User.MaxLengthFor.PasswordSalt);
     resultUser.PasswordHash = this._hashGenerator.GetPasswordHash(
         viewModel.Password,
         resultUser.PasswordSalt);
     return resultUser;
 }
Пример #17
0
    static int SetLevel(Profile player)
    {
        int totalPoints = 0;
        float attackPoints = 0;
        float defendPoints = 0;
        float meditatePoints = 0;
        for (int i = 0; i < 3; i++){
            attackPoints += player.attackList[i].basePower;
        }
        attackPoints /= 6;
        for (int i = 3; i < player.attackList.Count; i++){
            meditatePoints += player.attackList[i].basePower;
        }
        meditatePoints /= 6;

        for (int i = 0; i < player.defendList.Count; i++){
            defendPoints += player.defendList[i].baseDefense;
        }
        defendPoints /= 6;
        totalPoints = (int)(attackPoints + defendPoints + meditatePoints);
        totalPoints += player.hpMax / 5;
        totalPoints += player.enduranceMax / 5;
        totalPoints += player.enduranceRegen;
        return totalPoints;
    }
Пример #18
0
        public ActionResult Add(Profile model)
        {
            try
            {
                if (Request.Form["ProfileTypeId"] == "3")
                {

                    return RedirectToAction("Begin", "Twitter", new { serviceInterval = Convert.ToInt32(Request.Form["Interval"]) });
                }
                else if (Request.Form["ProfileTypeId"] == "2")
                {
                    return RedirectToAction("Index", "Google");
                }
                Session["ProfileTypeId"] = Request.Form["ProfileTypeId"];
                PageId = Request.Form["PageId"];
                ServiceInterval = Convert.ToInt32(Request.Form["Interval"]);
                SetPagePermissions();
                return Json("Success");

            }
            catch (Exception ex)
            {
                JavaScriptSerializer jss = new JavaScriptSerializer();
                return Json("Fail");
                // throw ex;
            }
        }
Пример #19
0
        public void TestAuthenticateInsecureLoginDisallowed()
        {
            using (var server = new ImapPseudoServer()) {
            server.Start();

            var prof = new Profile(new NetworkCredential("user", "pass"), "user;auth=*", server.HostPort);

            prof.UsingSaslMechanisms = new[] {"LOGIN", "PLAIN", "CRAM-MD5"};
            prof.AllowInsecureLogin = false;

            // greeting
            server.EnqueueResponse("* OK ready\r\n");
            // CAPABILITY response
            server.EnqueueResponse("* CAPABILITY IMAP4rev1 AUTH=X-UNKNOWN AUTH=DIGEST-MD5 AUTH=CRAM-MD5 AUTH=NTLM AUTH=PLAIN AUTH=LOGIN\r\n" +
                               "0000 OK done\r\n");
            // AUTHENTICATE CRAM-MD5 response
            server.EnqueueResponse("+ PDQwMDEzNDQxMTIxNDM1OTQuMTI3MjQ5OTU1MEBsb2NhbGhvc3Q+\r\n");
            server.EnqueueResponse("* CAPABILITY IMAP4rev1\r\n" +
                               "0001 OK done\r\n");

            using (var session = ImapSessionCreator.CreateSession(prof, null, null)) {
              Assert.AreEqual(ImapSessionState.Authenticated, session.State);
              Assert.AreEqual(prof.Authority, session.Authority);
            }

            server.DequeueRequest(); // CAPABILITY
            StringAssert.Contains("AUTHENTICATE CRAM-MD5", server.DequeueRequest());
              }
        }
Пример #20
0
    protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
    {
        InfoControl.Web.Security.MembershipManager mManager = new InfoControl.Web.Security.MembershipManager(this);
        InfoControl.Web.Security.DataEntities.User user = mManager.GetUserByName(CreateUserWizard1.UserName.ToString());

        Profile profile = new Profile();
        ProfileManager pManager = new ProfileManager(this);

        profile.Name = (CreateUserWizard1.FindControl("txtName") as TextBox).Text;
        profile.CPF = (CreateUserWizard1.FindControl("txtCPF") as TextBox).Text;
        //profile.Address = (CreateUserWizard1.FindControl("txtAddress") as TextBox).Text;
        profile.Phone = (CreateUserWizard1.FindControl("txtPhone") as TextBox).Text;
        //profile.Neighborhood = (CreateUserWizard1.FindControl("txtNeighborhood") as TextBox).Text;
        profile.PostalCode = (CreateUserWizard1.FindControl("txtPostalCode") as TextBox).Text;
        profile.ModifiedDate = DateTime.Now;        
        //profile.UserId = user.UserId;
        //profile.StateId = (CreateUserWizard1.FindControl("cboState") as DropDownList).SelectedValue;

        try
        {
            pManager.Insert(profile);
        }
        catch (Exception ex)
        {
            if (ex != null)
                return;
        }

        Context.Items.Add("UserId", user.UserId);
        Server.Transfer("User.aspx");
    }
Пример #21
0
        public void TestAuthenticateAnonymousMechanismSpecified()
        {
            using (var server = new ImapPseudoServer()) {
            server.Start();

            var prof = new Profile(null, "user%40imap.example.net;auth=anonymous", server.HostPort);

            // greeting
            server.EnqueueResponse("* OK ready\r\n");
            // CAPABILITY response
            server.EnqueueResponse("* CAPABILITY IMAP4rev1 AUTH=ANONYMOUS\r\n" +
                               "0000 OK done\r\n");
            // AUTHENTICATE response
            server.EnqueueResponse("+ \r\n");
            server.EnqueueResponse("* CAPABILITY IMAP4rev1\r\n" +
                               "0001 OK done\r\n");

            using (var session = ImapSessionCreator.CreateSession(prof, null, null)) {
              Assert.AreEqual(ImapSessionState.Authenticated, session.State);
              Assert.AreEqual(prof.Authority, session.Authority);
            }

            server.DequeueRequest(); // CAPABILITY
            StringAssert.Contains("AUTHENTICATE ANONYMOUS", server.DequeueRequest());
            StringAssert.Contains("*****@*****.**", Base64.GetDecodedString(server.DequeueRequest()));
              }
        }
Пример #22
0
        public void TestAuthenticateAnonymousMechanismSpecifiedAuthenticationFailure()
        {
            using (var server = new ImapPseudoServer()) {
            server.Start();

            var prof = new Profile(null, "user%40imap.example.net;auth=anonymous", server.HostPort);

            // greeting
            server.EnqueueResponse("* OK ready\r\n");
            // CAPABILITY response
            server.EnqueueResponse("* CAPABILITY IMAP4rev1 AUTH=ANONYMOUS\r\n" +
                               "0000 OK done\r\n");
            // AUTHENTICATE response
            server.EnqueueResponse("+ \r\n");
            server.EnqueueResponse("0001 NO done\r\n");

            try {
              Assert.IsNull(ImapSessionCreator.CreateSession(prof, null, null));
              Assert.Fail("ImapAuthenticationException not thrown");
            }
            catch (ImapAuthenticationException ex) {
              Assert.IsNull(ex.InnerException);
              Assert.IsNotNull(ex.Result);
              Assert.AreEqual(Protocol.Client.ImapCommandResultCode.No, ex.Result.Code);
            }

            server.DequeueRequest(); // CAPABILITY
            StringAssert.Contains("AUTHENTICATE ANONYMOUS", server.DequeueRequest());
            StringAssert.Contains("*****@*****.**", Base64.GetDecodedString(server.DequeueRequest()));
              }
        }
Пример #23
0
    void Start()
    {
        player = GameObject.FindObjectOfType<Player>();
        profile = GameObject.FindObjectOfType<Profile>();
        dotSpawner = GameObject.FindObjectOfType<DotSpawner>();
        feerieSpawner = GameObject.FindObjectOfType<FeerieSpawner>();
        message = GameObject.Find("Message").GetComponent<Text>();
        timeButtons = RectTransform.FindObjectsOfType<Button>();

        Button[] newTimeButtons = new Button[timeButtons.Length];
        for (int i = 0; i < timeButtons.Length; i++)
        {
            for (int j = 0; j < timeButtons.Length; j++)
            {
                if (timeButtons[j].name.Contains((i + 1).ToString()))
                {
                    newTimeButtons[i] = timeButtons[j];
                    break;
                }
            }
        }
        timeButtons = newTimeButtons;
        hideButtons();
        dotSpawner.setMode(DotSpawner.ModeSpawner.silent);
        //feerieSpawner.setSilence(true);
        startTimer = 0f;
        started = false;
        unlocked = false;
        Screen.sleepTimeout = 10;

    }
Пример #24
0
        public GreedState FoundPortal()
        {
            if (ProfileManager.CurrentProfile.Path != _GreedProfile && ProfileManager.CurrentProfile.Path != _GreedProfileBackUp)
            {
                Logger.Log("Loading Greed Profile - " + DateTime.Now.ToString());

                _currentProfile = ProfileManager.CurrentProfile;

                LoadProfile(_GreedProfile, true, 1);

                if (ProfileManager.CurrentProfile.Path != _GreedProfile)
                    LoadProfile(_GreedProfileBackUp, true, 1);
            }

            if (ZetaDia.CurrentWorldId != 379962 && ZetaDia.CurrentWorldId != 380753)
            {
                DiaObject portalObject = ZetaDia.Actors.RActorList.OfType<DiaObject>().FirstOrDefault(r => r.ActorSNO == _GreedPortalSNO);

                if (portalObject != null && !ZetaDia.Me.IsInCombat)
                {
                    Logger.Log("Moving to portal - Distance " + (int)ZetaDia.Me.Position.Distance2D(portalObject.Position) + " feet away");
                    Navigator.MoveTo(portalObject.Position);

                    PauseBot(0, 300);

                    portalObject.Interact();

                    PauseBot(0, 300);
                }
            }
            else
                return GreedState.InsidePortal;

            return ConfirmWorld();
        }
Пример #25
0
 public void saveExistingProfile(Profile profileToBeSaved)
 {
     BinaryFormatter bf = new BinaryFormatter();
     FileStream file = File.Open(Application.dataPath + "/../Profiles/" + profileToBeSaved.getFileName(), FileMode.Create);
     bf.Serialize(file, profileToBeSaved);
     file.Close();
 }
Пример #26
0
        public static Profile getProfile(XmlDocument doc )
        {
            XmlElement root = doc.DocumentElement;
            XmlNodeList list = root.SelectNodes("//publishProfile");

            Profile profiledata = new Profile();

            foreach (XmlNode node in list)
            {

                if (node.Attributes["profileName"].Value.Contains("Web Deploy"))
                {
                    profiledata.userPwd = node.Attributes["userPWD"].Value;
                    profiledata.userName = node.Attributes["userName"].Value;
                    profiledata.mysqlConnectionstring = node.Attributes["mySQLDBConnectionString"].Value;
                    profiledata.sqlazureconnectionstring = node.Attributes["SQLServerDBConnectionString"].Value;
                    profiledata.publishUrl = node.Attributes["publishUrl"].Value;
                    profiledata.sitename = node.Attributes["msdeploySite"].Value;
                    profiledata.destinationUrl = node.Attributes["destinationAppUrl"].Value;

                    return profiledata;

                }

            }
            return null;
        }
Пример #27
0
        public static void SyncDatabases(Profile src, Profile dest , string dbtype)
        {
            DeploymentSyncOptions syncOptions = new DeploymentSyncOptions();
            DeploymentBaseOptions destBaseOptions = new DeploymentBaseOptions();
            DeploymentBaseOptions sourceBaseOptions = new DeploymentBaseOptions();
            destBaseOptions.Trace += TraceEventHandler;
            sourceBaseOptions.Trace += TraceEventHandler;
            destBaseOptions.TraceLevel = TraceLevel.Verbose;
            sourceBaseOptions.TraceLevel = TraceLevel.Verbose;

            DeploymentProviderOptions destProviderOptions = null;

            DeploymentObject sourceObj = null;
            if (dbtype.Equals("mysql", StringComparison.InvariantCultureIgnoreCase))
            {
                destProviderOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.DBMySql);
                destProviderOptions.Path = dest.mysqlConnectionstring;
               sourceObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.DBMySql, src.mysqlConnectionstring, sourceBaseOptions);

            }
            else if (dbtype.Equals("sql", StringComparison.InvariantCultureIgnoreCase))
            {
                destProviderOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.DBFullSql);
                destProviderOptions.Path = dest.sqlazureconnectionstring;
                sourceObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.DBFullSql,src.sqlazureconnectionstring, sourceBaseOptions);
            }
            if (sourceObj != null)
            {

                sourceObj.SyncTo(destProviderOptions, destBaseOptions, syncOptions);

            }
        }
Пример #28
0
        public void CreateNewProfile(string newProfileName)
        {
            Profile newProfile = new Profile(newProfileName, 0);
            string[] profileParser = new string[_Profiles.Count + 1];

            string profileLineConvention = newProfile.ProfileName + "[&]";
            profileLineConvention += 0 + "[&]";
            profileParser[0] = profileLineConvention;
            for (int i = 0; i < _Profiles.Count; i++)
            {
                profileLineConvention = _Profiles[i].ProfileName + "[&]";
                profileLineConvention += _Profiles[i].CampaignProgress + "[&]";
                profileParser[i + 1] = profileLineConvention;
            }

            if (!System.IO.Directory.Exists(pathToDirectory))
                System.IO.Directory.CreateDirectory(pathToDirectory);
            try
            {
                System.IO.File.WriteAllLines(pathToProfiles, profileParser);
                //Clear list
                _Profiles.Clear();
                //Load new list with new profiles
                ParseProfile();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Пример #29
0
        public MainViewModel()
        {
            Model = new PlotModel();

            var profile = new Profile(Gender.Male, 80);

            var start = DateTime.Now.AddHours(-5);

            var drinks = new List<DrinkEntry> {
                new DrinkEntry(DrinkType.Beer, start.AddMinutes(5), 330.0, 4.6),
                new DrinkEntry(DrinkType.Beer, start.AddMinutes(25), 330.0, 4.6),
                new DrinkEntry(DrinkType.Beer, start.AddMinutes(50), 330.0, 4.6),
                new DrinkEntry(DrinkType.Beer, start.AddMinutes(75), 330.0, 4.6),
                new DrinkEntry(DrinkType.Spirits, start.AddMinutes(90), 40.0, 40.0)
            };

            var result = Library.Promillekoll.calculateAlcoholLevelOverTime(profile, ListModule.OfSeq(drinks));
            var series = new LineSeries("Alcohol Level");

            foreach (var entry in result)
            {
                var minutesSinceFirstDrink = entry.Item1.Subtract(start).TotalMinutes;
                series.Points.Add(new DataPoint(minutesSinceFirstDrink, entry.Item2));
            }
            Model.Series.Add(series);
        }
Пример #30
0
        /// <summary>
        /// Meldet alle Quellen zu einem Geräteprofil vorbereitet zur Anzeige.
        /// </summary>
        /// <param name="profile">Das gewünschte Geräteprofil.</param>
        /// <returns>Die sortierte Liste aller Quellen.</returns>
        public static List<SourceItem> CreateSortedListFromProfile( Profile profile )
        {
            // Create list
            List<SourceItem> items =
                profile
                    .AllSources
                    .Where( s => { Station st = (Station) s.Source; return st.IsService || (st.SourceType != SourceTypes.Unknown); } )
                    .Select( s => new SourceItem( s ) )
                    .ToList();

            // Sort by unique name
            items.Sort( ( l, r ) => string.Compare( l.Source.QualifiedName, r.Source.QualifiedName, StringComparison.InvariantCultureIgnoreCase ) );

            // Link together
            for (int i = 0; i < items.Count; )
            {
                // Back
                if (i > 0)
                    items[i].PreviousSource = items[i - 1].Source;

                // Forward
                if (++i < items.Count)
                    items[i - 1].NextSource = items[i].Source;
            }

            // Report
            return items;
        }
Пример #31
0
 public override List <LayerModel> GetRenderLayers(bool renderMice, bool renderHeadsets)
 {
     return(Profile.GetRenderLayers <Witcher3DataModel>(DataModel, renderMice, renderHeadsets));
 }
Пример #32
0
 public DeveloperDataIdMesg() : base(Profile.GetMesg(MesgNum.DeveloperDataId))
 {
 }
Пример #33
0
 public void Mapping(Profile profile)
 {
     profile.CreateMap <Product, ProductViewModel>();
 }
Пример #34
0
 public static void Map(Profile profile)
 {
     profile.CreateMap <DeezerUser, DeezerUserViewModel>();
 }
Пример #35
0
 public void Mapping(Profile profile)
 {
     profile.CreateMap<AuthenticationOption, AuthenticationOptionDetailDto>()
         .ForMember(d => d.AuthenticationOptionId, opt => opt.MapFrom(e => e.AuthenticationOptionId));
 }
Пример #36
0
        public void MinOSVersion(Profile profile, MachO.LoadCommands load_command, MachO.Platform platform, bool device = false)
        {
            if (device)
            {
                Configuration.AssertDeviceAvailable();
            }

            var machoFiles = Directory.GetFiles(Configuration.GetSdkPath(profile, device), "*", SearchOption.AllDirectories)
                             .Where((v) => {
                if (v.Contains("dylib.dSYM/Contents/Resources/DWARF"))
                {
                    // Don't include *.dylib from inside .dSYMs.
                    return(false);
                }
                else if (v.Contains("libxammac-classic") || v.Contains("libxammac-system-classic"))
                {
                    // We don't care about XM Classic, those are binary dependencies.
                    return(false);
                }
                var ext = Path.GetExtension(v);
                return(ext == ".a" || ext == ".dylib");
            }
                                    );

            var failed = new List <string> ();

            foreach (var machoFile in machoFiles)
            {
                var fatfile = MachO.Read(machoFile);
                foreach (var slice in fatfile)
                {
                    var any_load_command = false;
                    foreach (var lc in slice.load_commands)
                    {
                        Version lc_min_version;
                        var     mincmd = lc as MinCommand;
                        if (mincmd != null)
                        {
                            Assert.AreEqual(load_command, mincmd.Command, "Unexpected min load command");
                            lc_min_version = mincmd.Version;
                        }
                        else
                        {
                            // starting from iOS SDK 12 the LC_BUILD_VERSION is used instead
                            var buildver = lc as BuildVersionCommand;
                            if (buildver == null)
                            {
                                continue;
                            }

                            var alternativePlatform = (MachO.Platform) 0;
                            switch (platform)
                            {
                            case MachO.Platform.IOSSimulator:
                                alternativePlatform = MachO.Platform.IOS;
                                break;

                            case MachO.Platform.TvOSSimulator:
                                alternativePlatform = MachO.Platform.TvOS;
                                break;

                            case MachO.Platform.WatchOSSimulator:
                                alternativePlatform = MachO.Platform.WatchOS;
                                break;
                            }
                            Assert.That(buildver.Platform, Is.EqualTo(platform).Or.EqualTo(alternativePlatform), $"Unexpected build version command in {machoFile} ({slice.Filename})");
                            lc_min_version = buildver.MinOS;
                        }

                        Version version;
                        Version alternate_version = null;
                        Version mono_native_compat_version;
                        Version mono_native_unified_version;
                        switch (load_command)
                        {
                        case MachO.LoadCommands.MinMacOSX:
                            version = SdkVersions.MinOSXVersion;
                            mono_native_compat_version  = SdkVersions.MinOSXVersion;
                            mono_native_unified_version = new Version(10, 12, 0);
                            break;

                        case MachO.LoadCommands.MiniPhoneOS:
                            version = SdkVersions.MiniOSVersion;
                            if (slice.IsDynamicLibrary && device)
                            {
                                if (version.Major < 7)
                                {
                                    version = new Version(7, 0, 0);                                      // dylibs are supported starting with iOS 7.
                                }
                                alternate_version = new Version(8, 0, 0);                                // some iOS dylibs also have min OS 8.0 (if they're used as frameworks as well).
                            }
                            else if (slice.Architecture == MachO.Architectures.ARM64)
                            {
                                alternate_version = new Version(7, 0, 0);                                  // our arm64 slices has min iOS 7.0.
                            }
                            mono_native_compat_version  = SdkVersions.MiniOSVersion;
                            mono_native_unified_version = new Version(10, 0, 0);
                            break;

                        case MachO.LoadCommands.MintvOS:
                            version = SdkVersions.MinTVOSVersion;
                            mono_native_compat_version  = SdkVersions.MinTVOSVersion;
                            mono_native_unified_version = new Version(10, 0, 0);
                            break;

                        case MachO.LoadCommands.MinwatchOS:
                            version = SdkVersions.MinWatchOSVersion;
                            mono_native_compat_version  = SdkVersions.MinWatchOSVersion;
                            mono_native_unified_version = new Version(5, 0, 0);
                            break;

                        default:
                            throw new NotImplementedException(load_command.ToString());
                        }

                        version = version.WithBuild();
                        mono_native_compat_version  = mono_native_compat_version.WithBuild();
                        mono_native_unified_version = mono_native_unified_version.WithBuild();
                        if (alternate_version == null)
                        {
                            alternate_version = version;
                        }

                        switch (Path.GetFileName(machoFile))
                        {
                        case "libmono-native-compat.dylib":
                        case "libmono-native-compat.a":
                            if (mono_native_compat_version != lc_min_version)
                            {
                                failed.Add($"Unexpected minOS version (expected {mono_native_compat_version}, found {lc_min_version}) in {machoFile} ({slice.Filename}).");
                            }
                            break;

                        case "libmono-native-unified.dylib":
                        case "libmono-native-unified.a":
                            if (mono_native_unified_version != lc_min_version)
                            {
                                failed.Add($"Unexpected minOS version (expected {mono_native_unified_version}, found {lc_min_version}) in {machoFile} ({slice.Filename}).");
                            }
                            break;

                        default:
                            if (version != lc_min_version && alternate_version != lc_min_version)
                            {
                                failed.Add($"Unexpected minOS version (expected {version}, alternatively {alternate_version}, found {lc_min_version}) in {machoFile} ({slice.Filename}).");
                            }
                            break;
                        }
                        any_load_command = true;
                    }
                    if (!any_load_command)
                    {
                        failed.Add($"No minOS version found in {machoFile}.");
                    }
                }
            }
            CollectionAssert.IsEmpty(failed, "Failures");
        }
Пример #37
0
 private void OnGetProfileJson(Profile profile, Dictionary <string, object> customData = null)
 {
     Log.Debug("ExamplePersonaltyInsights.OnGetProfileJson()", "Personality Insights - GetProfileJson Response: {0}", customData["json"].ToString());
     Test(profile != null);
     _getProfileJsonTested = true;
 }
 private ProfileSetting GetImportProfileSetting(uint settingId, Profile importProfile)
 {
     return(importProfile.Settings
            .FirstOrDefault(x => x.SettingId.Equals(settingId)));
 }
        static async Task Main(string[] args)
        {
            Console.WriteLine("NextGenSoftware.OASIS.API.Core Test Harness v1.0");
            Console.WriteLine("");

            OASISAPIManager OASISAPIManager = new OASISAPIManager(new List <IOASISProvider> {
                new HoloOASIS("ws://*****:*****@nextgensoftware.co.uk", Password = "******", FirstName = "David", LastName = "Ellams", DOB = "11/04/1980", Id = Guid.NewGuid(), Title = "Mr", PlayerAddress = "blahahahaha"
            };


            await newProfile.KarmaEarnt(KarmaTypePositive.HelpingTheEnvironment, KarmaSourceType.hApp, "Our World", "XR Educational Game To Make The World A Better Place");

            Profile savedProfile = (Profile)await OASISAPIManager.ProfileManager.SaveProfileAsync(newProfile);

            //IProfile savedProfile = await profileManager.SaveProfileAsync(newProfile);

            if (savedProfile != null)
            {
                Console.WriteLine("Profile Saved.\n");
                Console.WriteLine(string.Concat("Id: ", savedProfile.Id));
                Console.WriteLine(string.Concat("Provider Key: ", savedProfile.ProviderKey));
                // Console.WriteLine(string.Concat("HC Address Hash: ", savedProfile.HcAddressHash)); //But we can still view the HC Hash if we wish by casting to the provider profile object as we have above. - UPDATE: We do not need this, the ProviderKey shows the same info (hash in this case).
                Console.WriteLine(string.Concat("Name: ", savedProfile.Title, " ", savedProfile.FirstName, " ", savedProfile.LastName));
                Console.WriteLine(string.Concat("Username: "******"Password: "******"Email: ", savedProfile.Email));
                Console.WriteLine(string.Concat("DOB: ", savedProfile.DOB));
                Console.WriteLine(string.Concat("Address: ", savedProfile.PlayerAddress));
                Console.WriteLine(string.Concat("Karma: ", savedProfile.Karma));
                Console.WriteLine(string.Concat("Level: ", savedProfile.Level));
            }

            Console.WriteLine("\nLoading Profile...");
            //IProfile profile = await profileManager.LoadProfileAsync("dellams", "1234");
            IProfile profile = await OASISAPIManager.ProfileManager.LoadProfileAsync("QmR6A1gkSmCsxnbDF7V9Eswnd4Kw9SWhuf8r4R643eDshg");

            if (profile != null)
            {
                Console.WriteLine("Profile Loaded.\n");
                Console.WriteLine(string.Concat("Id: ", profile.Id));
                Console.WriteLine(string.Concat("Provider Key: ", savedProfile.ProviderKey));
                //Console.WriteLine(string.Concat("HC Address Hash: ", profile.HcAddressHash)); //ProfileManager is independent of provider implementation so it should not know about HC Hash.
                Console.WriteLine(string.Concat("Name: ", profile.Title, " ", profile.FirstName, " ", profile.LastName));
                Console.WriteLine(string.Concat("Username: "******"Password: "******"Email: ", profile.Email));
                Console.WriteLine(string.Concat("DOB: ", profile.DOB));
                Console.WriteLine(string.Concat("Address: ", profile.PlayerAddress));
                Console.WriteLine(string.Concat("Karma: ", profile.Karma));
                Console.WriteLine(string.Concat("Level: ", profile.Level));
            }



            Console.ReadKey();
        }
 private bool ExistsImportValue(uint settingId, Profile importProfile)
 {
     return(importProfile.Settings
            .Any(x => x.SettingId.Equals(settingId)));
 }
        private Profile GetNewProfile(Guid?profileId = null)
        {
            Profile profile = new Profile(profileId ?? Guid.NewGuid(), Genre.Male, GetAvatarImage(), "Lucas Pereira Campos", "lucasnsbr", GetEmailAddress(), DateTime.Now.AddYears(-21));

            return(profile);
        }
 private bool ExistsImportApp(string appName, Profile importProfile)
 {
     return(importProfile.Executeables.Any(x => x.Equals(appName)));
 }
Пример #43
0
        public static void Inizialize(ISession Session)
        {
            #region Customer Inizialize
            Customer WallStreetDaily = new Customer
            {
                Id   = 1,
                Name = "Wall Street Daily"
            };
            Customer FleetStreetPublication = new Customer {
                Id = 2, Name = "Fleet Street Publication"
            };
            Customer DailyEdge = new Customer {
                Id = 3, Name = "Daily Edge"
            };
            Customer HeidiShubert = new Customer {
                Id = 6, Name = "Heidi Shubert"
            };
            Customer WeissResearch = new Customer {
                Id = 4, Name = "Weiss Research"
            };
            Customer WSD = new Customer {
                Id = 5, Name = "WSD Custom Strategy"
            };

            Session.Save(DailyEdge);
            Session.Save(HeidiShubert);
            Session.Save(WallStreetDaily);
            Session.Save(WeissResearch);
            Session.Save(WSD);
            Session.Save(FleetStreetPublication);
            #endregion

            #region Portfolios Inizialize
            Portfolio portfolio1 = new Portfolio
            {
                Id             = 1,
                Name           = "Strategic Investment Open Portfolio",
                Notes          = "A portfolio is a grouping of financial assets such as stocks,",
                DisplayIndex   = 1,
                LastUpdateDate = new DateTime(2017, 4, 28),
                Visibility     = false,
                Quantity       = 2,
                PercentWins    = 73.23m,
                BiggestWinner  = 234.32m,
                BiggestLoser   = 12.65m,
                AvgGain        = 186.65m,
                MonthAvgGain   = 99.436m,
                PortfolioValue = 1532.42m,
                Customer       = WallStreetDaily
            };

            Portfolio portfolio2 = new Portfolio
            {
                Id             = 2,
                Name           = "Strategic Investment Income Portfolio",
                Notes          = "A portfolio is a grouping of financial assets such as stocks,",
                DisplayIndex   = 2,
                LastUpdateDate = new DateTime(2017, 3, 12),
                Visibility     = true,
                Quantity       = 3,
                PercentWins    = 93.23m,
                BiggestWinner  = 534.32m,
                BiggestLoser   = 123.46m,
                AvgGain        = 316.65m,
                MonthAvgGain   = 341.436m,
                PortfolioValue = 5532.42m,
                Customer       = WallStreetDaily
                                 //Positions = new List<Position> { position3, position4, position5 }
            };
            Portfolio portfolio3 = new Portfolio
            {
                Id             = 3,
                Name           = "HDFC Bank",
                DisplayIndex   = 4,
                LastUpdateDate = new DateTime(2017, 3, 12),
                Visibility     = true,
                Quantity       = 3,
                PercentWins    = 93.23m,
                BiggestWinner  = 534.32m,
                BiggestLoser   = 123.46m,
                AvgGain        = 316.65m,
                MonthAvgGain   = 341.436m,
                PortfolioValue = 5532.42m,
                Customer       = WallStreetDaily
            };
            Portfolio portfolio4 = new Portfolio
            {
                Id             = 4,
                Name           = "IndusInd Bank",
                DisplayIndex   = 5,
                LastUpdateDate = new DateTime(2017, 3, 12),
                Visibility     = true,
                Quantity       = 3,
                PercentWins    = 93.23m,
                BiggestWinner  = 534.32m,
                BiggestLoser   = 123.46m,
                AvgGain        = 316.65m,
                MonthAvgGain   = 341.436m,
                PortfolioValue = 5532.42m,
                Customer       = FleetStreetPublication
            };
            Portfolio portfolio5 = new Portfolio
            {
                Id             = 5,
                Name           = "UltraTechCement",
                DisplayIndex   = 3,
                LastUpdateDate = new DateTime(2017, 3, 12),
                Visibility     = true,
                Quantity       = 3,
                PercentWins    = 93.23m,
                BiggestWinner  = 534.32m,
                BiggestLoser   = 123.46m,
                AvgGain        = 316.65m,
                MonthAvgGain   = 341.436m,
                PortfolioValue = 5532.42m,
                Customer       = FleetStreetPublication
            };

            Session.Save(portfolio1);
            Session.Save(portfolio2);
            Session.Save(portfolio3);
            Session.Save(portfolio4);
            Session.Save(portfolio5);
            #endregion

            #region Positions Inizialize
            Position position1 = new Position
            {
                Id              = 1,
                SymbolId        = 3,
                SymbolType      = Symbols.Option,
                SymbolName      = "PLSE",
                Name            = "Pulse Biosciences CS",
                OpenDate        = new DateTime(2015, 7, 20),
                OpenPrice       = 128.32m,
                OpenWeight      = 40,
                TradeType       = TradeTypes.Long,
                TradeStatus     = TradeStatuses.Open,
                Dividends       = 57.3m,
                CurrentPrice    = 99.53m,
                Gain            = 87.12m,
                AbsoluteGain    = 110.34m,
                MaxGain         = 154.34m,
                LastUpdateDate  = new DateTime(2016, 1, 1),
                LastUpdatePrice = 218.32m,
                Portfolio       = portfolio1
            };
            Position position2 = new Position
            {
                Id              = 2,
                SymbolId        = 2,
                SymbolType      = Symbols.Stock,
                SymbolName      = "WIWTY",
                Name            = "Witwatersrand Gold Rsrcs Ltd ",
                OpenDate        = new DateTime(2009, 2, 24),
                OpenPrice       = 4.00m,
                OpenWeight      = 125,
                TradeType       = TradeTypes.Long,
                TradeStatus     = TradeStatuses.Open,
                Dividends       = 0.00m,
                CurrentPrice    = 3.64m,
                Gain            = 40.0m,
                AbsoluteGain    = 1.60m,
                MaxGain         = 1.60m,
                LastUpdateDate  = new DateTime(2016, 1, 1),
                LastUpdatePrice = 218.32m,
                Portfolio       = portfolio1
            };
            Position position3 = new Position
            {
                Id              = 3,
                SymbolId        = 1,
                SymbolType      = Symbols.Option,
                SymbolName      = "AAT",
                Name            = "AAT Corporation Limited",
                OpenDate        = new DateTime(2017, 4, 28),
                OpenPrice       = 43.20m,
                OpenWeight      = 113,
                TradeType       = TradeTypes.Long,
                TradeStatus     = TradeStatuses.Wait,
                Dividends       = 17.34m,
                CloseDate       = new DateTime(2017, 5, 2),
                ClosePrice      = 54.24m,
                Gain            = 11.56m,
                AbsoluteGain    = 9.45m,
                MaxGain         = 14.34m,
                LastUpdateDate  = new DateTime(2016, 5, 1),
                LastUpdatePrice = 53.32m,
                Portfolio       = portfolio2
            };
            Position position4 = new Position
            {
                Id              = 4,
                SymbolId        = 4,
                SymbolType      = Symbols.Stock,
                SymbolName      = "FXI",
                Name            = "iShares FTSE/XINHUA 25",
                OpenDate        = new DateTime(2009, 8, 28),
                OpenPrice       = 39.81m,
                OpenWeight      = 65,
                TradeType       = TradeTypes.Long,
                TradeStatus     = TradeStatuses.Close,
                Dividends       = 1.54m,
                CloseDate       = new DateTime(2012, 1, 12),
                ClosePrice      = 36.74m,
                Gain            = 3.84m,
                AbsoluteGain    = 3.65m,
                MaxGain         = 3.65m,
                LastUpdateDate  = new DateTime(2011, 10, 11),
                LastUpdatePrice = 53.32m,
                Portfolio       = portfolio2
            };
            Position position5 = new Position
            {
                Id           = 1,
                SymbolId     = 3,
                SymbolType   = Symbols.Option,
                SymbolName   = "DBA",
                Name         = "Powershares DB Agri Index",
                OpenDate     = new DateTime(2009, 10, 30),
                OpenPrice    = 25.57m,
                OpenWeight   = 72,
                TradeType    = TradeTypes.Short,
                TradeStatus  = TradeStatuses.Open,
                Dividends    = 0.00m,
                CloseDate    = new DateTime(2012, 1, 12),
                ClosePrice   = 29.25m,
                CurrentPrice = 12.56m,
                Gain         = 14.39m,
                AbsoluteGain = 11.34m,
                MaxGain      = 13.34m,
                Portfolio    = portfolio2
            };

            var position10 = (Position)position1.Clone();
            var position11 = (Position)position1.Clone();
            var position12 = (Position)position1.Clone();
            var position13 = (Position)position1.Clone();
            var position14 = (Position)position1.Clone();
            var position15 = (Position)position1.Clone();
            var position16 = (Position)position1.Clone();
            var position17 = (Position)position1.Clone();
            var position18 = (Position)position1.Clone();
            var position19 = (Position)position1.Clone();

            var position21 = (Position)position2.Clone();
            var position20 = (Position)position2.Clone();
            var position22 = (Position)position2.Clone();
            var position23 = (Position)position2.Clone();
            var position24 = (Position)position2.Clone();
            var position25 = (Position)position2.Clone();
            var position26 = (Position)position2.Clone();
            var position27 = (Position)position2.Clone();
            var position28 = (Position)position2.Clone();
            var position29 = (Position)position2.Clone();

            Session.Save(position1);
            Session.Save(position10);
            Session.Save(position11);
            Session.Save(position12);
            Session.Save(position13);
            Session.Save(position14);
            Session.Save(position15);
            Session.Save(position16);
            Session.Save(position17);
            Session.Save(position18);
            Session.Save(position19);
            Session.Save(position20);
            Session.Save(position21);
            Session.Save(position22);
            Session.Save(position23);
            Session.Save(position24);
            Session.Save(position25);
            Session.Save(position26);
            Session.Save(position27);
            Session.Save(position28);
            Session.Save(position29);
            Session.Save(position2);
            Session.Save(position3);
            Session.Save(position4);
            Session.Save(position5);
            #endregion

            #region ColumnFormat Inizialize
            ColumnFormat None = new ColumnFormat
            {
                Id   = 1,
                Name = "None"
            };

            ColumnFormat Money = new ColumnFormat
            {
                Id   = 2,
                Name = "Money"
            };
            ColumnFormat Linked = new ColumnFormat
            {
                Id   = 3,
                Name = "Linked"
            };
            ColumnFormat Date = new ColumnFormat
            {
                Id   = 4,
                Name = "Date"
            };
            ColumnFormat DateAndTime = new ColumnFormat
            {
                Id   = 6,
                Name = "DateAndTime"
            };
            ColumnFormat Percent = new ColumnFormat
            {
                Id   = 7,
                Name = "Percent"
            };

            Session.Save(None);
            Session.Save(Money);
            Session.Save(Linked);
            Session.Save(Date);
            Session.Save(DateAndTime);
            Session.Save(Percent);

            #endregion

            #region Formats Inizialize

            Format DateFormat = new Format
            {
                Id            = 1,
                Name          = "Date Format",
                ColumnFormats = new List <ColumnFormat> {
                    Date, Linked, DateAndTime
                }
            };
            Format MoneyFormat = new Format
            {
                Id            = 2,
                Name          = "Money Format",
                ColumnFormats = new List <ColumnFormat> {
                    None, Money, Linked
                }
            };
            Format PercentFormat = new Format
            {
                Id            = 3,
                Name          = "Percent Format",
                ColumnFormats = new List <ColumnFormat> {
                    None, Percent
                }
            };
            Format NoneFormat = new Format
            {
                Id            = 4,
                Name          = "None Format",
                ColumnFormats = new List <ColumnFormat> {
                    None
                }
            };
            Format LineFormat = new Format
            {
                Id            = 5,
                Name          = "Line Format",
                ColumnFormats = new List <ColumnFormat> {
                    None, Linked
                }
            };

            Session.Save(DateFormat);
            Session.Save(MoneyFormat);
            Session.Save(PercentFormat);
            Session.Save(NoneFormat);
            Session.Save(LineFormat);
            #endregion

            #region ViewTemplate Inizialize
            ViewTemplate viewTemplate1 = new ViewTemplate
            {
                Id                 = 1,
                Name               = "Preview all",
                Positions          = TemplatePositions.All,
                ShowPortfolioStats = true,
                SortOrder          = Sorting.ASC,
                Customer           = WallStreetDaily
            };

            ViewTemplate viewTemplate2 = new ViewTemplate
            {
                Id                 = 2,
                Name               = "Default",
                Positions          = TemplatePositions.OpenOnly,
                ShowPortfolioStats = false,
                SortOrder          = Sorting.DESC,
                Customer           = WallStreetDaily
            };

            Session.Save(viewTemplate1);
            Session.Save(viewTemplate2);
            #endregion

            #region Columns Inizialize

            Column Name = new Column
            {
                Id     = 1,
                Name   = "Name",
                Format = LineFormat,
                //ViewTemplateColumns = new List<ViewTemplateColumn> { viewTemplateColumn1, viewTemplateColumn21 }
            };
            Column SymbolName = new Column
            {
                Id     = 2,
                Name   = "Symbol Name",
                Format = LineFormat,
                //ViewTemplateColumns = new List<ViewTemplateColumn> { viewTemplateColumn2 }
            };
            Column OpenPrice = new Column
            {
                Id     = 3,
                Name   = "Open Price",
                Format = MoneyFormat,
                //ViewTemplateColumns = new List<ViewTemplateColumn> { viewTemplateColumn3 }
            };
            Column OpenDate = new Column
            {
                Id     = 4,
                Name   = "Open Date",
                Format = DateFormat,
                //ViewTemplateColumns = new List<ViewTemplateColumn> { viewTemplateColumn4 }
            };
            Column OpenWeight = new Column
            {
                Id     = 5,
                Name   = "Open Weight",
                Format = NoneFormat,
                //ViewTemplateColumns = new List<ViewTemplateColumn> { viewTemplateColumn5 }
            };
            Column CurrentPrice = new Column
            {
                Id     = 6,
                Name   = "Current Price",
                Format = MoneyFormat,
                //ViewTemplateColumns = new List<ViewTemplateColumn> { viewTemplateColumn6 }
            };
            Column ClosePrice = new Column
            {
                Id     = 7,
                Name   = "Close Price",
                Format = MoneyFormat,
                // ViewTemplateColumns = new List<ViewTemplateColumn> { viewTemplateColumn7 }
            };
            Column CloseDate = new Column
            {
                Id     = 8,
                Name   = "Close Date",
                Format = DateFormat,
                //ViewTemplateColumns = new List<ViewTemplateColumn> { viewTemplateColumn8 }
            };
            Column TradeType = new Column
            {
                Id     = 9,
                Name   = "Trade Type",
                Format = NoneFormat,
                // ViewTemplateColumns = new List<ViewTemplateColumn> { viewTemplateColumn9 }
            };
            Column TradeStatus = new Column
            {
                Id     = 10,
                Name   = "Trade Status",
                Format = NoneFormat,
                //ViewTemplateColumns = new List<ViewTemplateColumn> { viewTemplateColumn10 }
            };
            Column Dividends = new Column
            {
                Id     = 11,
                Name   = "Dividends",
                Format = MoneyFormat,
                //ViewTemplateColumns = new List<ViewTemplateColumn> { viewTemplateColumn11 }
            };
            Column Gain = new Column
            {
                Id     = 12,
                Name   = "Gain",
                Format = MoneyFormat,
                //ViewTemplateColumns = new List<ViewTemplateColumn> { viewTemplateColumn12 }
            };
            Column AbsoluteGain = new Column
            {
                Id     = 13,
                Name   = "Absolute Gain",
                Format = PercentFormat,
                //ViewTemplateColumns = new List<ViewTemplateColumn> { viewTemplateColumn13 }
            };
            Column MaxGain = new Column
            {
                Id     = 14,
                Name   = "Max Gain",
                Format = MoneyFormat,
                //ViewTemplateColumns = new List<ViewTemplateColumn> { viewTemplateColumn14 }
            };
            Column LastUpdateDate = new Column
            {
                Id     = 15,
                Name   = "Last Update Date",
                Format = DateFormat,
                //ViewTemplateColumns = new List<ViewTemplateColumn> { viewTemplateColumn15 }
            };

            Column LastUpdatePrice = new Column
            {
                Id     = 16,
                Name   = "Last Update Price",
                Format = MoneyFormat,
                //ViewTemplateColumns = new List<ViewTemplateColumn> { viewTemplateColumn16 }
            };

            Session.Save(Name);
            Session.Save(SymbolName);
            Session.Save(OpenPrice);
            Session.Save(OpenDate);
            Session.Save(OpenWeight);
            Session.Save(CurrentPrice);
            Session.Save(ClosePrice);
            Session.Save(CloseDate);
            Session.Save(TradeType);
            Session.Save(TradeStatus);
            Session.Save(Dividends);
            Session.Save(Gain);
            Session.Save(AbsoluteGain);
            Session.Save(MaxGain);
            Session.Save(LastUpdateDate);
            Session.Save(LastUpdatePrice);
            #endregion

            #region ViewTemplateColumns Inizialize
            ViewTemplateColumn viewTemplateColumn1 = new ViewTemplateColumn
            {
                Id             = 1,
                Name           = "Name",
                ColumnEntiy    = Name,
                ViewTemplateId = 1,
                DisplayIndex   = 1,
                ColumnFormat   = Linked,
                ColumnId       = 1,
                ColumnFormatId = 3,
                ViewTemplate   = viewTemplate1,
                //ViewTemplatesForSorting = new List<ViewTemplate> { viewTemplate1 }
            };
            ViewTemplateColumn viewTemplateColumn2 = new ViewTemplateColumn
            {
                Id             = 2,
                Name           = "Symbol",
                ColumnEntiy    = SymbolName,
                ViewTemplateId = 1,
                DisplayIndex   = 2,
                ColumnFormat   = None,
                ColumnId       = 2,
                ColumnFormatId = 1,
                ViewTemplate   = viewTemplate1
            };
            ViewTemplateColumn viewTemplateColumn3 = new ViewTemplateColumn
            {
                Id             = 4,
                Name           = "Open Price",
                ColumnEntiy    = OpenPrice,
                ViewTemplateId = 1,
                DisplayIndex   = 4,
                ColumnFormat   = Money,
                ColumnId       = 3,
                ColumnFormatId = 2,
                ViewTemplate   = viewTemplate1
            };
            ViewTemplateColumn viewTemplateColumn4 = new ViewTemplateColumn
            {
                Id             = 5,
                Name           = "Open Date",
                ColumnEntiy    = OpenDate,
                ViewTemplateId = 1,
                DisplayIndex   = 5,
                ColumnFormat   = Date,
                ColumnId       = 4,
                ColumnFormatId = 4,
                ViewTemplate   = viewTemplate1
            };
            ViewTemplateColumn viewTemplateColumn5 = new ViewTemplateColumn
            {
                Id             = 3,
                Name           = "Weight",
                ColumnEntiy    = OpenWeight,
                ViewTemplateId = 1,
                DisplayIndex   = 3,
                ColumnFormat   = None,
                ColumnId       = 5,
                ColumnFormatId = 1,
                ViewTemplate   = viewTemplate1
            };
            ViewTemplateColumn viewTemplateColumn6 = new ViewTemplateColumn
            {
                Id             = 6,
                Name           = "Current Price",
                ColumnEntiy    = CurrentPrice,
                ViewTemplateId = 1,
                DisplayIndex   = 6,
                ColumnFormat   = Linked,
                ColumnId       = 6,
                ColumnFormatId = 3,
                ViewTemplate   = viewTemplate1
            };
            ViewTemplateColumn viewTemplateColumn7 = new ViewTemplateColumn
            {
                Id             = 7,
                Name           = "Close Price",
                ColumnEntiy    = ClosePrice,
                ViewTemplateId = 1,
                DisplayIndex   = 7,
                ColumnFormat   = None,
                ColumnId       = 7,
                ColumnFormatId = 1,
                ViewTemplate   = viewTemplate1
            };
            ViewTemplateColumn viewTemplateColumn8 = new ViewTemplateColumn
            {
                Id             = 8,
                Name           = "Close Date",
                ColumnEntiy    = CloseDate,
                ViewTemplateId = 1,
                DisplayIndex   = 8,
                ColumnFormat   = DateAndTime,
                ColumnId       = 8,
                ColumnFormatId = 6,
                ViewTemplate   = viewTemplate1
            };
            ViewTemplateColumn viewTemplateColumn9 = new ViewTemplateColumn
            {
                Id             = 9,
                Name           = "Trade Type",
                ColumnEntiy    = TradeType,
                ViewTemplateId = 1,
                DisplayIndex   = 9,
                ColumnFormat   = None,
                ColumnId       = 9,
                ColumnFormatId = 1,
                ViewTemplate   = viewTemplate1
            };
            ViewTemplateColumn viewTemplateColumn10 = new ViewTemplateColumn
            {
                Id             = 10,
                Name           = "Trade Status",
                ColumnEntiy    = TradeStatus,
                ViewTemplateId = 1,
                DisplayIndex   = 10,
                ColumnFormat   = None,
                ColumnId       = 10,
                ColumnFormatId = 1,
                ViewTemplate   = viewTemplate1
            };
            ViewTemplateColumn viewTemplateColumn11 = new ViewTemplateColumn
            {
                Id             = 11,
                Name           = "Dividends",
                ColumnEntiy    = Dividends,
                ViewTemplateId = 1,
                DisplayIndex   = 11,
                ColumnFormat   = Money,
                ColumnId       = 11,
                ColumnFormatId = 2,
                ViewTemplate   = viewTemplate1
            };
            ViewTemplateColumn viewTemplateColumn12 = new ViewTemplateColumn
            {
                Id             = 12,
                Name           = "Absolute Gain",
                ColumnEntiy    = AbsoluteGain,
                ViewTemplateId = 1,
                DisplayIndex   = 12,
                ColumnFormat   = Percent,
                ColumnId       = 13,
                ColumnFormatId = 7,
                ViewTemplate   = viewTemplate1
            };
            ViewTemplateColumn viewTemplateColumn13 = new ViewTemplateColumn
            {
                Id             = 13,
                Name           = "Max Gain",
                ColumnEntiy    = MaxGain,
                ViewTemplateId = 1,
                DisplayIndex   = 13,
                ColumnFormat   = Money,
                ColumnId       = 14,
                ColumnFormatId = 2,
                ViewTemplate   = viewTemplate1
            };
            ViewTemplateColumn viewTemplateColumn14 = new ViewTemplateColumn
            {
                Id             = 14,
                Name           = "Gain",
                ColumnEntiy    = Gain,
                ViewTemplateId = 1,
                DisplayIndex   = 14,
                ColumnFormat   = Linked,
                ColumnId       = 12,
                ColumnFormatId = 3,
                ViewTemplate   = viewTemplate1
            };
            ViewTemplateColumn viewTemplateColumn15 = new ViewTemplateColumn
            {
                Id             = 15,
                Name           = "Last Update Date",
                ColumnEntiy    = LastUpdateDate,
                ViewTemplateId = 1,
                DisplayIndex   = 15,
                ColumnFormat   = DateAndTime,
                ColumnId       = 15,
                ColumnFormatId = 6,
                ViewTemplate   = viewTemplate1
            };

            ViewTemplateColumn viewTemplateColumn16 = new ViewTemplateColumn
            {
                Id             = 16,
                Name           = "Last Update Price",
                ColumnEntiy    = LastUpdatePrice,
                ViewTemplateId = 1,
                DisplayIndex   = 16,
                ColumnFormat   = Linked,
                ColumnId       = 16,
                ColumnFormatId = 2,
                ViewTemplate   = viewTemplate1
            };
            ViewTemplateColumn viewTemplateColumn21 = new ViewTemplateColumn
            {
                Id             = 17,
                Name           = "Name",
                ColumnEntiy    = Name,
                ViewTemplateId = 2,
                DisplayIndex   = 1,
                ColumnFormat   = None,
                ColumnId       = 1,
                ColumnFormatId = 1,
                ViewTemplate   = viewTemplate2,
                //ViewTemplatesForSorting = new List<ViewTemplate> { viewTemplate2 }
            };
            Session.Save(viewTemplateColumn1);
            Session.Save(viewTemplateColumn2);
            Session.Save(viewTemplateColumn3);
            Session.Save(viewTemplateColumn4);
            Session.Save(viewTemplateColumn5);
            Session.Save(viewTemplateColumn6);
            Session.Save(viewTemplateColumn1);
            Session.Save(viewTemplateColumn7);
            Session.Save(viewTemplateColumn8);
            Session.Save(viewTemplateColumn9);
            Session.Save(viewTemplateColumn10);
            Session.Save(viewTemplateColumn11);
            Session.Save(viewTemplateColumn12);
            Session.Save(viewTemplateColumn13);
            Session.Save(viewTemplateColumn14);
            Session.Save(viewTemplateColumn15);
            Session.Save(viewTemplateColumn16);
            Session.Save(viewTemplateColumn21);
            #endregion

            #region View Inizialize

            ViewForTable previewAllView = new ViewForTable
            {
                Id                = 1,
                Name              = "Preview All View",
                ShowName          = true,
                DateFormat        = DateFormats.MonthDayYear,
                MoneyPrecision    = 2,
                PercentyPrecision = 4,
                ViewTemplate      = viewTemplate1,
                ViewTemplateId    = viewTemplate1.Id,
                Customer          = WallStreetDaily
            };

            ViewForTable defaultView = new ViewForTable
            {
                Id                = 2,
                Name              = "Default View",
                ShowName          = false,
                DateFormat        = DateFormats.DayMonthNameYear,
                MoneyPrecision    = 1,
                PercentyPrecision = 2,
                ViewTemplate      = viewTemplate2,
                ViewTemplateId    = viewTemplate2.Id,
                Customer          = WallStreetDaily
            };

            Session.Save(previewAllView);
            Session.Save(defaultView);
            #endregion

            #region User Inizialize
            var         userManager   = new ApplicationUserManager(new UserStore <UserEntity>(Session));
            var         roleManager   = new ApplicationRoleManager(new RoleStore <Role>(Session));
            List <Role> identityRoles = new List <Role>
            {
                new Role()
                {
                    Name = "Admin"
                },
                new Role()
                {
                    Name = "User"
                },
                new Role()
                {
                    Name = "Employee"
                }
            };

            foreach (Role role in identityRoles)
            {
                roleManager.Create(role);
            }
            UserEntity admin = new UserEntity {
                Email = "Admin", UserName = "******"
            };
            userManager.Create(admin, "Password");
            userManager.AddToRole(admin.Id, "Admin");
            userManager.AddToRole(admin.Id, "Employee");

            var clientProfile = new Profile
            {
                Id         = admin.Id,
                Login      = admin.UserName,
                Customer   = WallStreetDaily,
                CustomerId = WallStreetDaily.Id
            };
            WallStreetDaily.Profiles.Add(clientProfile);
            #endregion

            #region Records Inizialize
            Record record1 = new Record
            {
                UserId       = "1aaa023d-e950-47fc-9c3f-54fbffcc99cf",
                Entity       = Entities.Position,
                Operation    = Operations.Create,
                Successfully = true,
                EntityId     = 1,
                DateTime     = new DateTime(2017, 4, 1)
            };
            Record record2 = new Record
            {
                UserId       = "1aaa023d-e950-47fc-9c3f-54fbffcc99cf",
                Entity       = Entities.Position,
                Operation    = Operations.Delete,
                Successfully = false,
                EntityId     = 1,
                DateTime     = new DateTime(2017, 4, 3)
            };
            Record record3 = new Record
            {
                UserId       = "2da9e5e9-ee3e-473c-a131-c39050b26760",
                Entity       = Entities.Portfolio,
                Operation    = Operations.Update,
                Successfully = true,
                EntityId     = 2,
                DateTime     = new DateTime(2017, 4, 4)
            };
            Session.Save(record1);
            Session.Save(record2);
            Session.Save(record3);
            #endregion

            Session.Flush();

            #region View and function inizialize

            ISQLQuery createSymbolView = Session.CreateSQLQuery(
                "CREATE VIEW SymbolView AS " +
                "SELECT S.SymbolID, S.Symbol, S.Name, C.Symbol AS CurrencySymbol " +
                "FROM  HistoricalDataNew.dbo.Symbol AS S INNER JOIN " +
                "HistoricalDataNew.dbo.Currencies AS C ON S.CurrencyId = C.CurrencyId");

            ISQLQuery createSymbolDividends = Session.CreateSQLQuery(
                "CREATE VIEW SymbolDividends AS " +
                "SELECT    DividendAmount, SymbolID, TradeDate " +
                "FROM   HistoricalDataNew.dbo.Dividend");

            ISQLQuery createTradeSybolInformation = Session.CreateSQLQuery(
                "CREATE VIEW TradeSybolInformation AS " +
                "SELECT SymbolID, TradeDate, TradeIndex " +
                "FROM   HistoricalDataNew.dbo.IndexData " +
                "UNION " +
                "SELECT SymbolID, TradeDate, CAST(TradeOpen AS money) AS TradeIndex " +
                "FROM   HistoricalDataNew.dbo.StockData");

            ISQLQuery createGetPriceInDateInterval = Session.CreateSQLQuery(

                "CREATE FUNCTION[dbo].[getPriceDividendForSymbolInDateInterval](@dateFrom datetime, @dateTo datetime, @symbolId int) " +
                "RETURNS " +
                "@report TABLE(TradeDate datetime, Price MONEY, Dividends MONEY) " +
                "AS BEGIN " +
                "INSERT INTO @report SELECT DISTINCT tr.TradeDate, tr.TradeIndex AS Price, ISNULL(( " +
                "SELECT SUM(d.DividendAmount) " +

                "FROM SymbolDividends d " +

                "WHERE d.SymbolId = tr.SymbolId AND d.SymbolID = @symbolId AND " +

                "d.TradeDate = tr.TradeDate),0) AS Dividends " +

                "FROM TradeSybolInformation tr " +
                "WHERE tr.SymbolID = @symbolId  AND tr.TradeDate >= @dateFrom AND tr.TradeDate <= @dateTo " +

                "ORDER BY tr.TradeDate " +

                "RETURN " +
                "END ");

            ISQLQuery creategetMaxMinGain = Session.CreateSQLQuery(
                "CREATE FUNCTION[dbo].[getMaxMinGainForSymbolInDateInterval](@dateFrom datetime, @dateTo datetime, @symbolId int) " +
                "RETURNS " +
                "@report TABLE(TradeDate datetime, Price MONEY, Dividends MONEY) " +
                "AS BEGIN " +
                "DECLARE @tab TABLE(TradeDate datetime, Price MONEY, Dividends MONEY) " +

                "INSERT INTO @tab SELECT *FROM getPriceDividendForSymbolInDateInterval(@dateFrom, @dateTo, @symbolId) " +

                "INSERT INTO @report SELECT TOP 1 * FROM @tab " +
                "WHERE Price + Dividends = (SELECT MAX(Price + Dividends) FROM @tab) " +

                "INSERT INTO @report SELECT TOP 1 * FROM @tab " +
                "WHERE Price + Dividends = (SELECT MIN(Price + Dividends) FROM @tab) " +

                "RETURN " +
                "END");


            createSymbolView.ExecuteUpdate();
            createSymbolDividends.ExecuteUpdate();
            createTradeSybolInformation.ExecuteUpdate();
            createGetPriceInDateInterval.ExecuteUpdate();
            creategetMaxMinGain.ExecuteUpdate();

            #endregion
        }
Пример #44
0
 public void Mapping(Profile profile) =>
 profile.CreateMap <Topic, CategoryTopicVM>()
 .ForMember(d => d.Id, opt => opt.MapFrom(e => e.TopicId));
Пример #45
0
 public void Mapping(Profile profile)
 {
     profile.CreateMap <TodoItem, TodoItemDto>()
     .ForMember(d => d.Priority, opt => opt.MapFrom(s => (int)s.Priority));
 }
Пример #46
0
 public void CreateMappings(Profile configuration)
 {
     configuration.CreateMap <Uzsakymas, UzsakymasViewModel>();
 }
Пример #47
0
        private async Task <FaceToNamesChallenge> CreateFaceToNamesChallenge(List <Profile> profiles, Profile selectedProfile, int userId)
        {
            var employees   = profiles.Select(x => new Employee(x.Id, x.FirstName, x.LastName)).ToArray();
            var face        = new Face(selectedProfile.Image.Id, selectedProfile.Image.Url);
            var challengeId = await _gameRepository.CreateChallenge(selectedProfile.Id, userId).ConfigureAwait(false);

            return(new FaceToNamesChallenge(challengeId, GameConstants.FaceToNamesChallengeDescription, employees, face));
        }
 public void ConfigureMapping(Profile mapper)
 {
     mapper
     .CreateMap <Article, ArticleDetailsServiceModel>()
     .ForMember(a => a.Author, cfg => cfg.MapFrom(a => a.Author.UserName));
 }
Пример #49
0
        protected async void Start()
        {
            MainApp.BackEnabled = false;

            var profile = await Profile.New();

            tipStore = MainApp.LoadTipStore(profile);

            var titleLabel = new Label
            {
                Text  = "Welkom!",
                Style = StyleKit.AutoDarkLabelStyles.Display
            };

            var explainLabel = new Label
            {
                Text  = "Welkom bij je nieuwe app! Om te beginnen willen we je vragen om een aantal dingen in te stellen zodat de app beter op je persoonlijk afgestemd kan worden.",
                Style = StyleKit.AutoDarkLabelStyles.Body
            };

            var tpStyles    = StyleKit.AutoDarkStyles <TimePicker>();
            var entryStyles = StyleKit.AutoDarkStyles <Entry>();

            var topLayout = new StackLayout
            {
                Spacing         = StyleKit.AutoSpacing.Medium,
                VerticalOptions = LayoutOptions.Start,
                Children        =
                {
                    titleLabel,
                    explainLabel
                }
            };

            layout.Children.Add(topLayout);

            error = new Label
            {
                HorizontalTextAlignment = TextAlignment.Center,
                Style     = StyleKit.AutoDarkLabelStyles.Caption,
                TextColor = Color.Red,
                IsVisible = false,
            };

            nextButton = new Button
            {
                Text            = "Volgende",
                Style           = StyleKit.AutoLightButtonStyles.Body,
                TextColor       = Color.White,
                HeightRequest   = 4 * StyleKit.AutoSpacing.Small,
                BackgroundColor = Color.FromHex("fa5755"),
                VerticalOptions = LayoutOptions.EndAndExpand
            };

            var midLayout = new StackLayout
            {
                Spacing         = StyleKit.AutoSpacing.Medium,
                VerticalOptions = LayoutOptions.Start
            };

            layout.Children.Add(midLayout);

            layout.Children.Add(error);
            layout.Children.Add(nextButton);

            nextButton.IsEnabled = true;
            await nextButton.GetEventAsync <EventArgs>("Clicked");

            nextButton.IsEnabled = false;

            await PlatformSetup(titleLabel, explainLabel, nextButton);

            titleLabel.Text   = "Tips selecteren";
            explainLabel.Text = "Hier kan je instellen welke tips je nuttig lijken en je graag zou willen ontvangen." +
                                "\nVink deze tips aan en druk daarna op volgende om verder te gaan. Druk op de tekst van een tip om hem helemaal te lezen.";

            tipsList = new SelectTipsList
            {
                ItemsSource      = tipStore.GetAll(),
                InputTransparent = false,
            };

            error.GestureRecognizers.Add(new TapGestureRecognizer
            {
                Command = new Command(() => error.IsVisible = false)
            });

            //Oorzaak op android
            #if _IOS_
            tipsList.ItemAppearing += (sender, e) => error.IsVisible = false;
            #endif
            midLayout.Children.Add(tipsList);

            if (Device.Idiom == TargetIdiom.Phone)
            {
                midLayout.Padding = StyleKit.AutoPadding.With(top: 0, bottom: 0).Negative();
            }

            error.Text = "Vink alstublieft minstens drie tips aan om verder te gaan.";
            do
            {
                nextButton.IsEnabled = true;
                await nextButton.GetEventAsync <EventArgs>("Clicked");

                error.IsVisible      = true;
                nextButton.IsEnabled = false;
                error.IsVisible      = true;
            } while (tipStore.Count(tip => tip.Enabled) < 3);

            midLayout.Padding = 0;

            List <TimeSpan> tipsTimes = new List <TimeSpan>();

            #if __ANDROID__
            tipsList.ItemAppearing += (sender, e) => error.IsVisible = false;
            #endif

            error.IsVisible = false;

            Func <int, TimePicker> createTP = (int hours) => new TimePicker
            {
                Time   = TimeSpan.FromHours(hours),
                Format = "HH:mm",
#if __ANDROID__
                TextColor = Color.Black,
#endif
            };

            var timePickers = new List <TimePicker>();

            var timeGrid = new Grid
            {
                VerticalOptions   = LayoutOptions.Fill,
                RowDefinitions    = { },
                ColumnDefinitions =
                {
                    new ColumnDefinition {
                        Width = new GridLength(1, GridUnitType.Star)
                    },
                    new ColumnDefinition {
                        Width = new GridLength(2, GridUnitType.Star)
                    }
                }
            };

            Action <TimePicker> addTP = (tp) =>
            {
                int index = timePickers.Count;
                timePickers.Add(tp);
                tp.TextColor = Color.Black;
                timeGrid.RowDefinitions.Add(new RowDefinition {
                    Height = GridLength.Auto
                });

                Label timeGridLabel = new Label
                {
                    Text  = "Om: ",
                    Style = StyleKit.AutoDarkLabelStyles.Body,
                    #if __ANDROID__
                    TextColor = Color.Black,
                    #endif
                    HorizontalTextAlignment = TextAlignment.End,
                    VerticalTextAlignment   = TextAlignment.Center
                };

                timeGridLabel.TextColor = Color.Black;

                timeGrid.Children.Add(timeGridLabel, 0, index);
                timeGrid.Children.Add(tp, 1, index);
            };

            addTP(createTP(8));
            addTP(createTP(13));

            var addTime = new Button
            {
                Text    = "Nog een tijd toevoegen",
                Command = new Command(async() =>
                {
                    var tp = createTP(12);
                    addTP(tp);
                    tp.Focus();
                    //await scrollTimes.ScrollToAsync(tp, ScrollToPosition.MakeVisible, true);
                }),
                HorizontalOptions = LayoutOptions.CenterAndExpand,
                VerticalOptions   = LayoutOptions.Fill,
                HeightRequest     = 50
            };

            var scrollTimes = new ScrollView
            {
                Content = new StackLayout
                {
                    Children = { timeGrid, addTime }
                },
                VerticalOptions = LayoutOptions.FillAndExpand
            };

            titleLabel.Text   = "Tips selecteren";
            explainLabel.Text = "Deze tips worden gedurende de dag vernieuwd. Hieronder kan je aangeven op welke tijden je graag een tip wil ontvangen.";
            midLayout.Children.Clear();
            midLayout.Children.Add(scrollTimes);

            nextButton.IsEnabled = true;
            await nextButton.GetEventAsync <EventArgs>("Clicked");

            nextButton.IsEnabled = false;

            foreach (var tp in timePickers)
            {
                tipsTimes.Add(tp.Time);
            }

            var tipScheduler = new TipScheduler(profile, tipStore, tipsTimes);

            var morningTime = new TimePicker
            {
                Time   = TimeSpan.FromHours(9),
                Format = "HH:mm",
                Style  = tpStyles.Body
            };

            var eveningTime = new TimePicker
            {
                Time   = TimeSpan.FromHours(18),
                Format = "HH:mm",
                Style  = tpStyles.Body
            };

            timeGrid = new Grid
            {
                RowDefinitions =
                {
                    new RowDefinition {
                        Height = GridLength.Auto
                    },
                    new RowDefinition {
                        Height = GridLength.Auto
                    }
                },
                ColumnDefinitions =
                {
                    new ColumnDefinition {
                        Width = new GridLength(1, GridUnitType.Star)
                    },
                    new ColumnDefinition {
                        Width = new GridLength(1, GridUnitType.Star)
                    }
                }
            };
            timeGrid.Children.Add(new Label
            {
                Text  = "'s Ochtends om: ",
                Style = StyleKit.AutoDarkLabelStyles.Body,
                HorizontalTextAlignment = TextAlignment.End,
                VerticalTextAlignment   = TextAlignment.Center
            }, 0, 0);
            timeGrid.Children.Add(morningTime, 1, 0);
            timeGrid.Children.Add(new Label
            {
                Text  = "'s Avonds om: ",
                Style = StyleKit.AutoDarkLabelStyles.Body,
                HorizontalTextAlignment = TextAlignment.End,
                VerticalTextAlignment   = TextAlignment.Center
            }, 0, 1);
            timeGrid.Children.Add(eveningTime, 1, 1);

            titleLabel.Text   = "Stemmingscheck";
            explainLabel.Text = "Deze app zal je tweemaal daags vragen hoe het met je gaat. Als je een voorkeur hebt voor de tijd waarop dat gebeurt kan je deze hieronder opgeven.";
            midLayout.Children.Replace(timeGrid);

            nextButton.IsEnabled = true;
            await nextButton.GetEventAsync <EventArgs>("Clicked");

            nextButton.IsEnabled = false;

            var moodMonitor = new MoodMonitor(profile);
            moodMonitor.MorningCheck = morningTime.Time;
            moodMonitor.EveningCheck = eveningTime.Time;

            eveningTime = new TimePicker
            {
                Time   = TimeSpan.FromHours(20),
                Format = "HH:mm",
                Style  = tpStyles.Body
            };

            timeGrid = new Grid
            {
                RowDefinitions =
                {
                    new RowDefinition {
                        Height = GridLength.Auto
                    }
                },
                ColumnDefinitions =
                {
                    new ColumnDefinition {
                        Width = new GridLength(1, GridUnitType.Star)
                    },
                    new ColumnDefinition {
                        Width = new GridLength(1, GridUnitType.Star)
                    }
                }
            };
            timeGrid.Children.Add(new Label
            {
                Text  = "'s Avonds om: ",
                Style = StyleKit.AutoDarkLabelStyles.Body,
                HorizontalTextAlignment = TextAlignment.End,
                VerticalTextAlignment   = TextAlignment.Center
            }, 0, 0);
            timeGrid.Children.Add(eveningTime, 1, 0);

            titleLabel.Text   = "Dagevaluatie";
            explainLabel.Text = "Deze app zal je ook aan het einde van de dag vragen je activiteiten die dag te beoordelen. Als je een voorkeur hebt voor de tijd waarop dat gebeurt kan je deze hieronder opgeven.";
            midLayout.Children.Replace(timeGrid);

            nextButton.IsEnabled = true;
            await nextButton.GetEventAsync <EventArgs>("Clicked");

            nextButton.IsEnabled = false;

            var activityMonitor = new ActivityMonitor(profile);
            activityMonitor.Check = eveningTime.Time;

            midLayout.Children.Clear();

            /* For scrolling when keyboard is up */
            //page.Content = new ScrollView { Content = layout, InputTransparent = true };

            var passEntry = new Entry
            {
                Placeholder = "Uw gewenste pincode hier...",
                Keyboard    = Keyboard.Numeric,
                Style       = entryStyles.Body
            };

            titleLabel.Text   = "Pincode instellen";
            explainLabel.Text = "Vul hieronder a.u.b. een makkelijk te onthouden code van 4 cijfers in om de gegevens binnen de app persoonlijk te houden.";
            midLayout.Children.Add(
                passEntry
                );

            string passText = null;
            error.Text             = "Vul a.u.b. een geldige pincode in.";
            passEntry.TextChanged += (sender, e) =>
            {
                if (e.NewTextValue?.Length > 4)
                {
                    passEntry.Text = e.OldTextValue;
                }
                else
                {
                    error.IsVisible = false;
                }
            };

            do
            {
                nextButton.IsEnabled = true;
                await nextButton.GetEventAsync <EventArgs>("Clicked");

                nextButton.IsEnabled = false;
                passText             = passEntry.Text;
                error.IsVisible      = true;
            } while (!Coach.ValidPassword(passText));

            error.IsVisible = false;

            var password = Coach.HashPassword(passText);
            Preferences.Set(profile.ID + "_password", password);

            midLayout.Children.Remove(passEntry);

            var mailEntry = new Entry
            {
                Placeholder = "Uw e-mailadres hier...",
                Keyboard    = Keyboard.Email,
                Style       = entryStyles.Body
            };

            titleLabel.Text   = "E-mail instellen";
            explainLabel.Text = "Mocht je je pincode vergeten, willen wij je graag een nieuwe sturen zodat je de app kunt blijven gebruiken. Daarvoor hebben we jouw e-mailadres nodig.\nVul hieronder a.u.b. een e-mailadres in waar je toegang tot hebt, zodat je ook altijd toegang hebt tot de app.";
            midLayout.Children.Add(
                mailEntry
                );

            string mailText = null;

            /* error.Text = "Vul a.u.b. een geldige pincode in.";
             * passEntry.TextChanged += (sender, e) => {
             *  if (e.NewTextValue?.Length > 4)
             *      passEntry.Text = e.OldTextValue;
             *  else
             *      error.IsVisible = false;
             * }; */

            mailEntry.TextChanged += (sender, e) =>
            {
                var trimmed = mailEntry.Text.Trim();
                if (trimmed != mailEntry.Text)
                {
                    mailEntry.Text = trimmed;
                }
            };

            //do
            //{
            nextButton.IsEnabled = true;
            await nextButton.GetEventAsync <EventArgs>("Clicked");

            nextButton.IsEnabled = false;
            mailText             = mailEntry.Text;
            //error.IsVisible = true;
            //} while (!Coach.ValidPassword(passText));

            error.IsVisible = false;

            Preferences.Set(profile.ID + "_email", mailText);

            midLayout.Children.Remove(mailEntry);

            titleLabel.Text   = "Dank je wel!";
            explainLabel.Text = "Je bent klaar met instellen!\nDruk op volgende om de app te gaan gebruiken.";

            Preferences.Set("user", profile.ID);

            MainApp.BackEnabled = true;

            nextButton.IsEnabled = true;
            await nextButton.GetEventAsync <EventArgs>("Clicked");

            nextButton.IsEnabled = false;

            Navigation.PopModalAsync();

            MessagingCenter.Send(this, CoachPage.CoachMessage,
                                 new Coach(profile, tipStore, tipScheduler, new List <Monitor> {
                moodMonitor, activityMonitor
            }));
        }
 public ZonesTargetMesg() : base(Profile.GetMesg(MesgNum.ZonesTarget))
 {
 }
 public void Mapping(Profile profile)
 {
     profile.CreateMap <Domain.Model.Vehicle, UserCarsForList>()
     .ForMember(s => s.Name, opt => opt.MapFrom(x => string.Concat(x.VehicleBrandName.Name, " ", x.Model)));
 }
 public void ConfigureMapping(Profile mapper)
 => mapper.CreateMap <Course, CourseDetailsServiceModel>()
 .ForMember(c => c.Trainer, cfg => cfg.MapFrom(c => c.Trainer.UserName))
 .ForMember(c => c.Students, cfg => cfg.MapFrom(c => c.Students.Count));
Пример #53
0
        public void OriginUpdateTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                // Create clients
                var cdnMgmtClient   = CdnTestUtilities.GetCdnManagementClient(context, handler1);
                var resourcesClient = CdnTestUtilities.GetResourceManagementClient(context, handler2);

                // Create resource group
                var resourceGroupName = CdnTestUtilities.CreateResourceGroup(resourcesClient);

                // Create a standard cdn profile
                string  profileName      = TestUtilities.GenerateName("profile");
                Profile createParameters = new Profile
                {
                    Location = "WestUs",
                    Sku      = new Sku {
                        Name = SkuName.StandardVerizon
                    },
                    Tags = new Dictionary <string, string>
                    {
                        { "key1", "value1" },
                        { "key2", "value2" }
                    }
                };

                var profile = cdnMgmtClient.Profiles.Create(resourceGroupName, profileName, createParameters);

                // Create a cdn endpoint with minimum requirements
                string endpointName             = TestUtilities.GenerateName("endpoint");
                var    endpointCreateParameters = new Endpoint
                {
                    Location       = "WestUs",
                    IsHttpAllowed  = true,
                    IsHttpsAllowed = true,
                    Origins        = new List <DeepCreatedOrigin>
                    {
                        new DeepCreatedOrigin
                        {
                            Name     = "origin1",
                            HostName = "host1.hello.com"
                        }
                    }
                };

                var endpoint = cdnMgmtClient.Endpoints.Create(resourceGroupName, profileName, endpointName, endpointCreateParameters);

                // Update origin on running endpoint should succeed
                var originParameters = new OriginUpdateParameters
                {
                    HostName  = "www.bing.com",
                    HttpPort  = 1234,
                    HttpsPort = 8081
                };

                cdnMgmtClient.Origins.Update(resourceGroupName, profileName, endpointName, "origin1", originParameters);

                // Update origin with invalid hostname should fail
                originParameters = new OriginUpdateParameters
                {
                    HostName  = "invalid!Hostname&",
                    HttpPort  = 1234,
                    HttpsPort = 8081
                };

                Assert.ThrowsAny <ErrorResponseException>(() =>
                {
                    cdnMgmtClient.Origins.Update(resourceGroupName, profileName, endpointName, "origin1", originParameters);
                });

                // Stop endpoint should succeed
                cdnMgmtClient.Endpoints.Stop(resourceGroupName, profileName, endpointName);

                // Update origin on stopped endpoint should succeed
                originParameters = new OriginUpdateParameters
                {
                    HostName = "www.hello.com",
                    HttpPort = 1265
                };

                cdnMgmtClient.Origins.Update(resourceGroupName, profileName, endpointName, "origin1", originParameters);

                // Update origin with invalid ports should fail
                originParameters = new OriginUpdateParameters
                {
                    HttpPort  = 99999,
                    HttpsPort = -2000
                };

                Assert.ThrowsAny <ErrorResponseException>(() =>
                {
                    cdnMgmtClient.Origins.Update(resourceGroupName, profileName, endpointName, "origin1", originParameters);
                });

                // Delete resource group
                CdnTestUtilities.DeleteResourceGroup(resourcesClient, resourceGroupName);
            }
        }
Пример #54
0
        private async Task <bool> BackupToCloud()
        {
            System.Text.StringBuilder sb         = new System.Text.StringBuilder();
            System.Text.StringBuilder sbFailures = new System.Text.StringBuilder();
            List <EarnedGrauity>      lstUsersWithCloudBackup = EarnedGrauity.GratuitiesForUser(string.Empty, Gratuity.GratuityTypes.CloudBackup);

            if (!String.IsNullOrEmpty(UserRestriction))
            {
                lstUsersWithCloudBackup.RemoveAll(eg => eg.Username.CompareCurrentCultureIgnoreCase(UserRestriction) != 0);
            }

            foreach (EarnedGrauity eg in lstUsersWithCloudBackup)
            {
                StorageID sid = StorageID.None;
                if (eg.UserProfile != null && ((sid = eg.UserProfile.BestCloudStorage) != StorageID.None) && eg.CurrentStatus != EarnedGrauity.EarnedGratuityStatus.Expired)
                {
                    try
                    {
                        Profile pf = eg.UserProfile;

                        LogbookBackup lb = new LogbookBackup(pf);

                        switch (sid)
                        {
                        case StorageID.Dropbox:
                        {
                            try
                            {
                                MFBDropbox.TokenStatus ts = await new MFBDropbox().ValidateDropboxToken(pf, true, true);
                                if (ts == MFBDropbox.TokenStatus.None)
                                {
                                    continue;
                                }

                                Dropbox.Api.Files.FileMetadata result = null;
                                result = await lb.BackupToDropbox(Branding.CurrentBrand);

                                sb.AppendFormat(CultureInfo.CurrentCulture, "Dropbox: user {0} ", pf.UserName);
                                if (ts == MFBDropbox.TokenStatus.oAuth1)
                                {
                                    sb.Append("Token UPDATED from oauth1! ");
                                }
                                sb.AppendFormat(CultureInfo.CurrentCulture, "Logbook backed up for user {0}...", pf.UserName);
                                System.Threading.Thread.Sleep(0);
                                result = await lb.BackupImagesToDropbox(Branding.CurrentBrand);

                                System.Threading.Thread.Sleep(0);
                                sb.AppendFormat(CultureInfo.CurrentCulture, "and images backed up for user {0}.\r\n \r\n", pf.UserName);
                            }
                            catch (Dropbox.Api.ApiException <Dropbox.Api.Files.UploadError> ex)
                            {
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (Dropbox.Api.ApiException<Dropbox.Api.Files.UploadError) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                                string szMessage = (ex.ErrorResponse.IsPath && ex.ErrorResponse.AsPath != null && ex.ErrorResponse.AsPath.Value.Reason.IsInsufficientSpace) ? Resources.LocalizedText.DropboxErrorOutOfSpace : ex.Message;
                                util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                                Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, szMessage, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                            }
                            catch (Dropbox.Api.ApiException <Dropbox.Api.Auth.TokenFromOAuth1Error> ex)
                            {
                                // De-register dropbox.
                                pf.DropboxAccessToken = string.Empty;
                                pf.FCommit();
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (TokenFromOAuth1Error, token removed) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                                util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                                Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, Resources.LocalizedText.DropboxErrorDeAuthorized), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                            }
                            catch (Dropbox.Api.AuthException ex)
                            {
                                // De-register dropbox.
                                pf.DropboxAccessToken = string.Empty;
                                pf.FCommit();
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (AuthException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                                util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                                Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, Resources.LocalizedText.DropboxErrorDeAuthorized), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                            }
                            catch (Dropbox.Api.BadInputException ex)
                            {
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (BadInputException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                                util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                                Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), false, false);
                            }
                            catch (Dropbox.Api.HttpException ex)
                            {
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (HttpException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                                util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                                Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                            }
                            catch (Dropbox.Api.AccessException ex)
                            {
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (AccessException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                                util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                                Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                            }
                            catch (Dropbox.Api.DropboxException ex)
                            {
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (Base dropbox exception) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                                util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                                Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                            }
                            catch (UnauthorizedAccessException ex)
                            {
                                // De-register dropbox.
                                pf.DropboxAccessToken = string.Empty;
                                pf.FCommit();
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (UnauthorizedAccess) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                                util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                                Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, Resources.LocalizedText.DropboxErrorDeAuthorized), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                            }
                            catch (MyFlightbookException ex)
                            {
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (MyFlightbookException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                                util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                                Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                            }
                            catch (System.IO.FileNotFoundException ex)
                            {
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user: FileNotFoundException, no notification sent {0}: {1} {2}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message);
                            }
                            catch (Exception ex)
                            {
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (Unknown Exception), no notification sent {0}: {1} {2}\r\n\r\n{3}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message, ex.StackTrace);
                                if (ex.InnerException != null)
                                {
                                    sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Inner exception: {0}\r\n{1}", ex.InnerException.Message, ex.InnerException.StackTrace);
                                }
                            }
                        }
                        break;

                        case StorageID.OneDrive:
                        {
                            try
                            {
                                if (pf.OneDriveAccessToken == null)
                                {
                                    throw new UnauthorizedAccessException();
                                }

                                Microsoft.OneDrive.Sdk.Item item = null;
                                OneDrive od = new OneDrive(pf.OneDriveAccessToken);
                                item = await lb.BackupToOneDrive(od);

                                sb.AppendFormat(CultureInfo.CurrentCulture, "OneDrive: user {0} ", pf.UserName);
                                sb.AppendFormat(CultureInfo.CurrentCulture, "Logbook backed up for user {0}...", pf.UserName);
                                System.Threading.Thread.Sleep(0);
                                item = await lb.BackupImagesToOneDrive(od, Branding.CurrentBrand);

                                System.Threading.Thread.Sleep(0);
                                sb.AppendFormat(CultureInfo.CurrentCulture, "and images backed up for user {0}.\r\n \r\n", pf.UserName);

                                // if we are here we were successful, so save the updated refresh token
                                if (String.Compare(pf.OneDriveAccessToken.RefreshToken, od.AuthState.RefreshToken, StringComparison.Ordinal) != 0)
                                {
                                    pf.OneDriveAccessToken.RefreshToken = od.AuthState.RefreshToken;
                                    pf.FCommit();
                                }
                            }
                            catch (Microsoft.OneDrive.Sdk.OneDriveException ex)
                            {
                                string szMessage = OneDrive.MessageForException(ex);
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "OneDrive FAILED for user (OneDriveException) {0}: {1}\r\n\r\n", pf.UserName, szMessage + " " + ex.Message);
                                util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.OneDriveFailureSubject, ActiveBrand),
                                                Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.OneDriveFailure, pf.UserFullName, szMessage, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                            }
                            catch (MyFlightbookException ex)
                            {
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "OneDrive FAILED for user (MyFlightbookException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                                util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.OneDriveFailureSubject, ActiveBrand),
                                                Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.OneDriveFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                            }
                            catch (UnauthorizedAccessException ex)
                            {
                                // De-register oneDrive.
                                pf.OneDriveAccessToken = null;
                                pf.FCommit();
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "OneDrive FAILED for user (UnauthorizedAccess) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                                util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.OneDriveFailureSubject, ActiveBrand),
                                                Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.OneDriveFailure, pf.UserFullName, ex.Message, Resources.LocalizedText.DropboxErrorDeAuthorized), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                            }
                            catch (System.IO.FileNotFoundException ex)
                            {
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "OneDrive FAILED for user: FileNotFoundException, no notification sent {0}: {1} {2}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message);
                            }
                            catch (Exception ex)
                            {
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "OneDrive FAILED for user (Unknown Exception), no notification sent {0}: {1} {2}\r\n\r\n{3}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message, ex.StackTrace);
                            }
                        }
                        break;

                        case StorageID.GoogleDrive:
                        {
                            try
                            {
                                if (pf.GoogleDriveAccessToken == null)
                                {
                                    throw new UnauthorizedAccessException();
                                }

                                GoogleDrive gd         = new GoogleDrive(pf.GoogleDriveAccessToken);
                                bool        fRefreshed = await gd.RefreshAccessToken();

                                sb.AppendFormat(CultureInfo.CurrentCulture, "GoogleDrive: user {0} ", pf.UserName);
                                IReadOnlyDictionary <string, string> meta = await lb.BackupToGoogleDrive(gd, Branding.CurrentBrand);

                                if (meta != null)
                                {
                                    sb.AppendFormat(CultureInfo.CurrentCulture, "Logbook backed up for user {0}...", pf.UserName);
                                }
                                System.Threading.Thread.Sleep(0);
                                meta = await lb.BackupImagesToGoogleDrive(gd, Branding.CurrentBrand);

                                System.Threading.Thread.Sleep(0);
                                if (meta != null)
                                {
                                    sb.AppendFormat(CultureInfo.CurrentCulture, "and images backed up for user {0}.\r\n \r\n", pf.UserName);
                                }

                                // if we are here we were successful, so save the updated refresh token
                                if (fRefreshed)
                                {
                                    pf.FCommit();
                                }
                            }
                            catch (MyFlightbookException ex)
                            {
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "GoogleDrive FAILED for user (MyFlightbookException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                                util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.GoogleDriveFailureSubject, ActiveBrand),
                                                Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.GoogleDriveFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                            }
                            catch (UnauthorizedAccessException ex)
                            {
                                // De-register GoogleDrive.
                                pf.GoogleDriveAccessToken = null;
                                pf.FCommit();
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "GoogleDrive FAILED for user (UnauthorizedAccess) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                                util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.GoogleDriveFailureSubject, ActiveBrand),
                                                Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.GoogleDriveFailure, pf.UserFullName, ex.Message, Resources.LocalizedText.DropboxErrorDeAuthorized), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                            }
                            catch (System.IO.FileNotFoundException ex)
                            {
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "GoogleDrive FAILED for user: FileNotFoundException, no notification sent {0}: {1} {2}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message);
                            }
                            catch (Exception ex)
                            {
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "GoogleDrive FAILED for user (Unknown Exception), no notification sent {0}: {1} {2}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message);
                            }
                        }
                        break;

                        case StorageID.iCloud:
                            break;

                        default:
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        string szError = String.Format(CultureInfo.CurrentCulture, "eg user={0}{1}\r\n\r\n{2}\r\n\r\n{3}", eg == null ? "NULL eg!" : eg.Username, (eg != null && eg.UserProfile == null) ? " NULL PROFILE" : string.Empty, sbFailures.ToString(), sb.ToString());
                        util.NotifyAdminException("ERROR running nightly backup", new Exception(szError, ex));
                    }
                }
            }
            ;

            util.NotifyAdminEvent("Dropbox report", sbFailures.ToString() + sb.ToString(), ProfileRoles.maskCanReport);
            return(true);
        }
Пример #55
0
 public ClientController(Profile profile)
     : base(profile)
 {
 }
Пример #56
0
 public NmeaSentenceMesg() : base(Profile.GetMesg(MesgNum.NmeaSentence))
 {
 }
Пример #57
0
 public HrMesg() : base(Profile.GetMesg(MesgNum.Hr))
 {
 }
Пример #58
0
        public void OriginGetListTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                // Create clients
                var cdnMgmtClient   = CdnTestUtilities.GetCdnManagementClient(context, handler1);
                var resourcesClient = CdnTestUtilities.GetResourceManagementClient(context, handler2);

                // Create resource group
                var resourceGroupName = CdnTestUtilities.CreateResourceGroup(resourcesClient);

                // Create a standard cdn profile
                string  profileName      = TestUtilities.GenerateName("profile");
                Profile createParameters = new Profile
                {
                    Location = "WestUs",
                    Sku      = new Sku {
                        Name = SkuName.StandardVerizon
                    },
                    Tags = new Dictionary <string, string>
                    {
                        { "key1", "value1" },
                        { "key2", "value2" }
                    }
                };

                var profile = cdnMgmtClient.Profiles.Create(resourceGroupName, profileName, createParameters);

                // Create a cdn endpoint with minimum requirements
                string endpointName             = TestUtilities.GenerateName("endpoint");
                var    endpointCreateParameters = new Endpoint
                {
                    Location       = "WestUs",
                    IsHttpAllowed  = true,
                    IsHttpsAllowed = true,
                    Origins        = new List <DeepCreatedOrigin>
                    {
                        new DeepCreatedOrigin
                        {
                            Name     = "origin1",
                            HostName = "host1.hello.com"
                        }
                    }
                };

                var endpoint = cdnMgmtClient.Endpoints.Create(resourceGroupName, profileName, endpointName, endpointCreateParameters);

                // Get origin on endpoint should return the deep created origin
                var origin = cdnMgmtClient.Origins.Get(resourceGroupName, profileName, endpointName, "origin1");
                Assert.NotNull(origin);

                // Get origins on endpoint should return one
                var origins = cdnMgmtClient.Origins.ListByEndpoint(resourceGroupName, profileName, endpointName);
                Assert.Single(origins);

                // Delete resource group
                CdnTestUtilities.DeleteResourceGroup(resourcesClient, resourceGroupName);
            }
        }
Пример #59
0
        public ActionResult Register(UserProfile userProfile)
        {
            if (ModelState.IsValid)
            {
                // Has email already been registered?
                var emailDuplicated = checkEmail(userProfile.Email);
                if (emailDuplicated == true)
                {
                    TempData["Message"] = userProfile.Email + Environment.NewLine + "This Email address has already been registered.";
                    return(RedirectToAction("Index"));
                }

                // Create the User Record
                User user = new Models.User();
                user.UserName = userProfile.UserName;
                user.Email    = userProfile.Email;
                user.Admin    = false;

                // Create a random password for this user
                UserInfo uInfo    = new UserInfo();
                string   password = uInfo.CreatePassword(6);
                user.Password = password;

                db.Users.Add(user);
                db.SaveChanges();

                // Create the Profile Record
                var newprofile = new Profile();
                newprofile.UserID     = user.UserID;
                newprofile.HomeClubID = userProfile.HomeCourseID;
                newprofile.Handicap   = userProfile.Handicap;
                newprofile.Photo      = "/Images/Default Profile Photo.jpg";
                db.Profiles.Add(newprofile);
                db.SaveChanges();

                // Create New Message to Inform Admin of NEW user
                MessageInfo messageInfo = new MessageInfo();

                var AllAdmin = uInfo.GetAllAdmin();

                string AdminEmail = "";
                string Subject    = "";
                string Body       = "";

                foreach (var item in AllAdmin)
                {
                    messageInfo.CreateMessage(newprofile.UserID, item.UserID, DateTime.Now, user.UserName + " has registered to join Tigerline Scores.");
                    AdminEmail = item.Email;
                    // Send Email to Admin
                    Subject = "NEW USER HAS REGISTERED";
                    Body    = "<span style='font-family: Calibri; font-size: 24px; font-weight: bold; color: green'>TIGERLINE SCORES</span><br/><br/>";
                    Body   += "<span style='font-family: Calibri'>New user " + user.UserName + " has registered to use Tigerline Scores..<br/><br/>";
                    Body   += "<a href='www.tigerlinescores.co.uk'>Tigerline Scores</a>";
                    messageInfo.SendEmail(AdminEmail, Subject, Body, null);
                }

                // Send email to new user with NEW password (created above) and instructions on how to use Tigerline Scores
                Body  = "<span style='font-family: Calibri; font-size: 24px; font-weight: bold; color: green'>TIGERLINE SCORES</span><br/><br/>";
                Body += "<div style='font-family: Calibri; font-size: 14px'>" + user.UserName + "<br/><br/>Thanks for registering and welcome to Tigerline Scores.<br/><br/>";
                Body += "Your login details are : <br/><br/>";
                Body += "<span style='font-weight: bold'>" + user.Email + "</span><br/>";
                Body += "Password  <span style='font-weight: bold'>" + password + "</span><br/><br/>";
                Body += "Attached to this email are instructions on how to find your way around the site, how to register an upcoming round and how to upload your score cards.<br/><br/>";
                Body += "I hope you enjoy using Tigerline Scores. Please feel free to send me any comments you have about the site as I am still developing and improving it.<br/>";
                Body += "Send your emails to [email protected]<br/><br/>";
                Body += "Thanks again and good luck!<br/><br/>Martin<br/><br/>";
                Body += "<a href='www.tigerlinescores.co.uk'>Tigerline Scores</a>";
                Body += "</div>";

                string userEmail = user.Email;
                Subject = "Welcome to Tigerline Scores";
                string attachment = Server.MapPath("~/Images/Tigerline_Scores_Instructions.pdf");
                messageInfo.SendEmail(userEmail, Subject, Body, attachment);


                TempData["Register"] = "Thanks for registering to join Tigerline Scores." + Environment.NewLine + "An email will be sent to you shortly with your password and information about how to use Tigerline Scores. Use your email address and the password to login into this site.";
                return(RedirectToAction("Index"));
            }
            return(View("Index"));
        }
Пример #60
0
 private string GetIso639(Profile p)
 {
     return(p.iso_639_1 == null ? string.Empty : p.iso_639_1.ToString());
 }