public void ClearForeignNetworkLinks(string ForeignID, Customer.ForeignUserTypes type)
        {
            try
            {
                TableServiceContextV2 clearContext = new TableServiceContextV2(client.BaseUri.ToString(), client.Credentials);

                string partitionKey = ((int)type).ToString() + "+" + ForeignID;
                partitionKey = partitionKey.ToLower();

                var f = (from e in clearContext.CreateQuery<CustomerForeignNetworkConnectionDb>(TableName) where e.PartitionKey == partitionKey select e).AsTableServiceQuery();

                List<string> custPartitions = new List<string>();

                foreach (CustomerForeignNetworkConnectionDb d in f)
                {
                    custPartitions.Add("Cust" + d.CustomerID.ToString());
                    clearContext.DeleteObject(d);
                }

                clearContext.SaveChangesWithRetries(SaveChangesOptions.Batch);

                foreach (string s in custPartitions)
                {
                    var c = (from e in context.CreateQuery<CustomerForeignNetworkConnectionDb>(TableName) where e.PartitionKey == s && e.RowKey == partitionKey select e).FirstOrDefault();
                    clearContext.DeleteObject(c);
                    clearContext.SaveChangesWithRetries();
                }

                clearContext = null;
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine("FOREIGN NETWORK EXCEPTION: " + e.ToString());
            }
        }
        public ChallengeStatus(ChallengeStatusDb d)
        {
            // this.UniqueID = d.RowKey;
            this.CustomerID = d.CustomerID;
            this.ChallengeID = d.ChallengeID;
            this.Status = d.Status;
            this.ChallengeOriginatorCustomerID = d.ChallengeOriginatorCustomerID;

            this.Customer = null;
        }
 public long Add(Customer c)
 {
     var p = CustToDynParm(c);
     using (SqlConnection db = new SqlConnection(connStr))
     {
         db.Open();
         p.Add("@InsertID", dbType: DbType.Int64, direction: ParameterDirection.Output);
         db.Execute("spCustomerAdd", p, commandType: CommandType.StoredProcedure);
         return p.Get<long>("@InsertID");
     }
 }
        public OnboardResult CompleteFirstStepForeignUserOnboard(string handle, Customer.ForeignUserTypes type, string token = null, string tokenSecret = null)
        {
            OnboardResult r = new OnboardResult();

            Customer c = RepoFactory.GetCustomerRepo().GetWithForeignUserID(handle, type);

            if (c == null)
            {
                Customer newCust = new Customer()
                {
                    ForeignUserID = handle,
                    ForeignUserType = (int)type,
                    Type = (int)Customer.TypeCodes.Unclaimed,
                    BillingType = (int)BillingSystem.BillingProcessorFactory.SupportedBillingProcessor.None
                };

                newCust.ID = RepoFactory.GetCustomerRepo().Add(newCust);

                RepoFactory.GetCustomerRepo().AddForeignNetworkForCustomer(newCust.ID, handle, type);

                r.Customer = newCust;
            }
            else
            {
                // we don't put this in the repo, we're just
                // using it as a DTO to get the token and secret
                // back to the controller
                r.Customer = c;
            }

            OnboardToken newToken = new OnboardToken()
            {
                CustomerID = r.Customer.ID,
                VerificationString = System.Guid.NewGuid().ToString(),
                Token = token,
                Secret = tokenSecret,
                AccountType = (int)type,
                ForeignUserID = handle
            };

            RepoFactory.GetOnboardTokenRepo().Add(newToken);

            r.OnboardToken = newToken;

            return r;
        }
        public void AddForeignNetworkForCustomer(long ID, string ForeignID, Customer.ForeignUserTypes type)
        {
            CustomerForeignNetworkConnection f = new CustomerForeignNetworkConnection { CustomerID = ID, UserID = ForeignID, Type = (int)type };

            // store it for both kinds of lookup:
            //      * by foreign ID
            //      * by customer ID
            //
            CustomerForeignNetworkConnectionDb fDB1 = new CustomerForeignNetworkConnectionDb(f, true);
            CustomerForeignNetworkConnectionDb fDB2 = new CustomerForeignNetworkConnectionDb(f, false);

            context.AttachTo(TableName, fDB1, null);
            context.AttachTo(TableName, fDB2, null);

            context.UpdateObject(fDB1);
            context.UpdateObject(fDB2);

            context.SaveChangesWithRetries();

            context.Detach(fDB1);
            context.Detach(fDB2);
        }
        private DynamicParameters CustToDynParm(Customer c, bool inclID=false)
        {
            var p = new DynamicParameters();

            if (c.FirstName == null)
                c.FirstName = "";
            if (c.LastName == null)
                c.LastName = "";
            if (c.EmailAddress == null)
                c.EmailAddress = "";
            if (c.Address == null)
                c.Address = "";
            if (c.Address2 == null)
                c.Address2 = "";
            if (c.City == null)
                c.City = "";
            if (c.State == null)
                c.State = "";
            if (c.ZIPCode == null)
                c.ZIPCode = "";
            if (c.FacebookAccessToken == null)
                c.FacebookAccessToken = "";
            if (c.FacebookExpires == null)
                c.FacebookExpires = "";
            if (c.FacebookUserID == null)
                c.FacebookUserID = "";
            if (c.Password == null)
                c.Password = "";
            if (c.BillingID == null)
                c.BillingID = "";
            if (c.AvatarURL == null)
                c.AvatarURL = "";

            p.Add("@FirstName", c.FirstName, dbType: DbType.String, direction: ParameterDirection.Input);
            p.Add("@LastName", c.LastName, dbType: DbType.String, direction: ParameterDirection.Input);
            p.Add("@EmailAddress", c.EmailAddress, dbType: DbType.String, direction: ParameterDirection.Input);
            p.Add("@Address", c.Address, dbType: DbType.String, direction: ParameterDirection.Input);
            p.Add("@Address2", c.Address2, dbType: DbType.String, direction: ParameterDirection.Input);
            p.Add("@City", c.City, dbType: DbType.String, direction: ParameterDirection.Input);
            p.Add("@State", c.State, dbType: DbType.String, direction: ParameterDirection.Input);
            p.Add("@ZIPCode", c.ZIPCode, dbType: DbType.String, direction: ParameterDirection.Input);
            p.Add("@FacebookAccessToken", c.FacebookAccessToken, dbType: DbType.String, direction: ParameterDirection.Input);
            p.Add("@FacebookExpires", c.FacebookExpires, dbType: DbType.String, direction: ParameterDirection.Input);
            p.Add("@FacebookUserID", c.FacebookUserID, dbType: DbType.String, direction: ParameterDirection.Input);
            p.Add("@Password", c.Password, dbType: DbType.String, direction: ParameterDirection.Input);
            p.Add("@BillingType", c.BillingType, dbType: DbType.Int32, direction: ParameterDirection.Input);
            p.Add("@BillingID", c.BillingID, dbType: DbType.String, direction: ParameterDirection.Input);
            p.Add("@Type", c.Type, dbType: DbType.Int32, direction: ParameterDirection.Input);
            p.Add("@AvatarURL", c.AvatarURL, dbType: DbType.String, direction: ParameterDirection.Input);
            p.Add("@ForeignUserType", c.ForeignUserType, dbType: DbType.Int32, direction: ParameterDirection.Input);
            if (inclID)
                p.Add("@ID", c.ID, dbType: DbType.Int64, direction: ParameterDirection.Input);

            return p;
        }
 public void Update(Customer c)
 {
     using (SqlConnection db = new SqlConnection(connStr))
     {
         db.Open();
         var p = CustToDynParm(c, true);
         db.Execute("spCustomerUpdate", p, commandType: CommandType.StoredProcedure);
     }
 }
        public void RemoveForeignNetworkForCustomer(long ID, string ForeignID, Customer.ForeignUserTypes type)
        {
            CustomerForeignNetworkConnection f = new CustomerForeignNetworkConnection { CustomerID = ID, UserID = ForeignID.ToLower(), Type = (int)type };

            CustomerForeignNetworkConnectionDb fDB1 = new CustomerForeignNetworkConnectionDb(f, true);
            CustomerForeignNetworkConnectionDb fDB2 = new CustomerForeignNetworkConnectionDb(f, false);

            context.AttachTo(TableName, fDB1);
            context.AttachTo(TableName, fDB2);

            context.DeleteObject(fDB1);
            context.SaveChangesWithRetries();

            context.DeleteObject(fDB2);
            context.SaveChangesWithRetries();
        }
 public Customer GetWithForeignUserID(string ID, Customer.ForeignUserTypes type)
 {
     return this.GetWithID(this.GetIDForForeignUserID(ID, type));
 }
        public long GetIDForForeignUserID(string ID, Customer.ForeignUserTypes type)
        {
            string partitionKey = ((int)type).ToString() + "+" + ID;
            partitionKey = partitionKey.ToLower();

            System.Diagnostics.Trace.WriteLine("Trying to find foreign user " + partitionKey);

            var f = (from e in context.CreateQuery<CustomerForeignNetworkConnectionDb>(TableName) where e.PartitionKey == partitionKey select e).FirstOrDefault<CustomerForeignNetworkConnectionDb>();

            if (f != null && f.CustomerID > 0)
            {
                System.Diagnostics.Trace.WriteLine("Found foreign user " + partitionKey + " with customer ID " + f.CustomerID.ToString());
                return f.CustomerID;
            }
            else
            {
                System.Diagnostics.Trace.WriteLine("Couldn't find foreign user " + partitionKey);
                return 0;
            }
        }
        public CustomerSignupResult HandleCredentialSignup(Customer newCustomer)
        {
            newCustomer.EmailAddress = newCustomer.EmailAddress.ToLower().Trim();

            Customer tryEmail = Repo.GetWithEmailAddress(newCustomer.EmailAddress);
            if (tryEmail != null && tryEmail.EmailAddress.Equals(newCustomer.EmailAddress))
            {
                if (tryEmail.Type != (int)Customer.TypeCodes.Unclaimed)
                    return new CustomerSignupResult { Customer = null, Result = CustomerSignupResult.ResultCode.EmailInUse };
            }

            newCustomer.Type = (int)Customer.TypeCodes.Unverified;

            try
            {
                newCustomer.Password = Security.GenerateV1PasswordHash(newCustomer.EmailAddress, newCustomer.Password);

                CoreCreateSendVerificationEmail(newCustomer);
                if (tryEmail == null)
                {
                    newCustomer.ID = Repo.Add(newCustomer);
                }
                else
                    Repo.Update(tryEmail);
            }
            catch (Exception e)
            {
                return new CustomerSignupResult { Result = CustomerSignupResult.ResultCode.Failed, Customer=null };
            }

            return new CustomerSignupResult { Result = CustomerSignupResult.ResultCode.Success, Customer = newCustomer };
        }
 public Audience DetermineAudience(Customer c)
 {
     return CoreDetermineAudience(c.ID);
 }
        public static Customer Filter(Customer c)
        {
            Customer filtered = new Customer();

            filtered.ID = c.ID;
            filtered.FirstName = c.FirstName;
            filtered.LastName = c.LastName;
            filtered.AvatarURL = c.AvatarURL;

            return filtered;
        }
        private Customer FilterForAudience(Customer c, Security.Audience Audience)
        {
            Customer filtered = new Customer();

            switch (Audience)
            {
                case Security.Audience.Anybody:
                    filtered.FirstName = c.FirstName;
                    filtered.LastName = c.LastName;
                    filtered.AvatarURL = c.AvatarURL;
                    filtered.ID = c.ID;
                    break;
                case Security.Audience.Friends:
                    filtered.FirstName = c.FirstName;
                    filtered.LastName = c.LastName;
                    filtered.AvatarURL = c.AvatarURL;
                    filtered.ID = c.ID;
                    break;
                case Security.Audience.Owner:
                    filtered = c;
                    filtered.Password = null;
                    break;
                case Security.Audience.Users:
                    filtered.FirstName = c.FirstName;
                    filtered.LastName = c.LastName;
                    filtered.AvatarURL = c.AvatarURL;
                    filtered.ID = c.ID;
                    break;
            }

            return filtered;
        }
        //[HttpPost]
        //public void Claim(
        /*
        private void CoreHandleFacebookSignup(Customer newCustomer)
        {
            Customer tryFB = Repo.GetWithFacebookID(newCustomer.FacebookUserID);

            // if we have an unclaimed FB user, claim them now
            // rather than making a new account.
            if (tryFB != null && tryFB.FacebookUserID == newCustomer.FacebookUserID)
            {
                tryFB.Type = (int)Customer.TypeCodes.Default;
                tryFB.FacebookAccessToken = newCustomer.FacebookAccessToken;
                tryFB.FacebookExpires = newCustomer.FacebookExpires;

                Repo.Update(tryFB);
            }
            else
            {
                Repo.Add(newCustomer);
            }

        }*/
        private void CoreCreateSendVerificationEmail(Customer newCustomer)
        {
            AuthorizationRepository authRepo = new AuthorizationRepository();

            Authorization a = new Authorization("verify-" + Guid.NewGuid().ToString());
            a.Valid = false;
            a.EmailAddress = newCustomer.EmailAddress;
            a.CustomerID = newCustomer.ID;

            authRepo.Add(a);

            String authUrl = "http://dareme.to/verify/" + a.Token;
        }
        public void Update(Customer profile)
        {
            Customer c = Repo.GetWithID(profile.ID);

            if (Security.DetermineAudience(c) != Security.Audience.Owner)
                throw new HttpResponseException(System.Net.HttpStatusCode.Forbidden);

            if(profile.FirstName!=null && !profile.FirstName.Equals(""))
                c.FirstName = profile.FirstName;

            if (profile.LastName != null && !profile.LastName.Equals(""))
                c.LastName = profile.LastName;

            if (profile.AvatarURL != null && !profile.AvatarURL.Equals(""))
                c.AvatarURL = profile.AvatarURL;

            if (profile.Address != null && !profile.Address.Equals(""))
                c.Address = profile.Address;

            if (profile.Address2 != null && !profile.Address2.Equals(""))
                c.Address2 = profile.Address2;

            if (profile.City != null && !profile.City.Equals(""))
                c.City = profile.City;

            if (profile.State != null && !profile.State.Equals(""))
                c.State = profile.State;

            if (profile.ZIPCode != null && !profile.ZIPCode.Equals(""))
                c.ZIPCode = profile.ZIPCode;

            Repo.Update(c);
        }
        public void Signup(Customer newCustomer)
        {
            if (newCustomer.AvatarURL == null || newCustomer.AvatarURL.Equals(""))
                newCustomer.AvatarURL = "http://images.dareme.to/avatars/default.jpg";

            if(newCustomer.Password==null || newCustomer.Password.Equals(""))
            {
                // no authentication details provided for this customer
                throw new HttpResponseException(System.Net.HttpStatusCode.InternalServerError);
            }

            //newCustomer.BillingType = (int)BillingSystem.BillingProcessorFactory.SupportedBillingProcessor.Stripe;
            newCustomer.BillingType = (int)BillingSystem.BillingProcessorFactory.SupportedBillingProcessor.None;

            if (newCustomer.FirstName == null || newCustomer.FirstName.Equals("") || newCustomer.LastName == null || newCustomer.LastName.Equals(""))
                throw new HttpResponseException(System.Net.HttpStatusCode.InternalServerError);

            CustomerSignupResult c=this.HandleCredentialSignup(newCustomer);

            if (c.Result != CustomerSignupResult.ResultCode.Success)
                throw new HttpResponseException(System.Net.HttpStatusCode.Forbidden);

            // send back a blank 200; the client should now try to authorize
        }
 public ChallengeStatus()
 {
     this.Customer = null;
 }
        public Challenge New(NewChallenge value)
        {
            if (value.Description.Equals(""))
            {
                Trace.WriteLine("EXCEPTION: You must specify a description for a challenge", "ChallengeController::New");

                throw new HttpResponseException(System.Net.HttpStatusCode.InternalServerError);
            }

            Challenge possibleDupe = ChalRepo.CheckForDuplicate(new Challenge() { Created=DateTime.Now, Description = value.Description, CustomerID = ((DareyaIdentity)HttpContext.Current.User.Identity).CustomerID, Privacy=value.Privacy });
            if (possibleDupe != null)
            {
                // F**K ME BRO.
                return possibleDupe;
            }

            Customer cust = CustRepo.GetWithID(((DareyaIdentity)HttpContext.Current.User.Identity).CustomerID);

            IBillingProcessor processor = BillingSystem.BillingProcessorFactory.GetBillingProcessor((BillingSystem.BillingProcessorFactory.SupportedBillingProcessor)cust.BillingType);
            if (processor == null)
            {
                // No billing processor exists to service this request. All challenges must originate from customers
                // that have set up their billing. Therefore we must reject this request outright.

                // let's be naughty and throw a "reserved for future use" HTTP status code.
                throw new HttpResponseException(System.Net.HttpStatusCode.PaymentRequired);
            }

            Trace.WriteLine("Creating a new challenge for customer " + ((DareyaIdentity)HttpContext.Current.User.Identity).CustomerID.ToString(), "ChallengeController::New");

            value.CustomerID = ((DareyaIdentity)HttpContext.Current.User.Identity).CustomerID;

            decimal firstBid = (decimal)value.CurrentBid;

            value.ID=ChalRepo.Add(value);

            decimal approxFees = Billing.GetFeesForBounty(processor, value.CurrentBid);

            Trace.WriteLine("Adding a bid of " + firstBid.ToString() + " to challenge ID " + value.ID.ToString(), "ChallengeController::New");
            ChalRepo.AddBidToChallenge(value, value.CustomerID, firstBid, approxFees);

            value.CurrentBid = (firstBid - approxFees);

            bool createTargetStatus=false;

            Trace.WriteLine("The target customer type for challenge " + value.ID.ToString() + " is " + value.ForeignNetworkType.ToString());

            // Try using a supplied email address to target the challenge first...
            if (value.EmailAddress != null && !value.EmailAddress.Equals(""))
            {
                value.EmailAddress = value.EmailAddress.ToLower().Trim();

                Customer tryEMail = CustRepo.GetWithEmailAddress(value.EmailAddress);
                if (tryEMail != null && tryEMail.EmailAddress.Equals(value.EmailAddress))
                {
                    Trace.WriteLine("Found the email customer " + value.EmailAddress + " for new challenge " + value.ID.ToString(), "ChallengeController::New");
                    value.TargetCustomerID = tryEMail.ID;
                }
                else
                {
                    Trace.WriteLine("Couldn't find the email customer " + value.EmailAddress + " for new challenge " + value.ID.ToString(), "ChallengeController::New");
                    Customer unclaimedEmail = new Customer();
                    unclaimedEmail.EmailAddress = value.EmailAddress;
                    unclaimedEmail.Type = (int)Customer.TypeCodes.Unclaimed;
                    value.TargetCustomerID = CustRepo.Add(unclaimedEmail);
                }
                createTargetStatus = true;
            }
            else // then try using a supplied foreign network connection...
            {
                if (value.ForeignNetworkType != Customer.ForeignUserTypes.Undefined)
                {
                    long fnCustID = CustRepo.GetIDForForeignUserID(value.ForeignNetworkUserID, value.ForeignNetworkType);
                    if (fnCustID > 0)
                    {
                        Trace.WriteLine("Found the foreign network customer " + value.ForeignNetworkUserID + " as customer ID " + fnCustID.ToString());
                        value.TargetCustomerID = fnCustID;
                    }
                    else
                    {
                        Customer unclaimedCust = new Customer
                        {
                            FirstName = value.FirstName,
                            LastName = value.LastName,
                            Type = (int)Customer.TypeCodes.Unclaimed,
                            ForeignUserType = (int)value.ForeignNetworkType
                        };

                        value.TargetCustomerID = CustRepo.Add(unclaimedCust);

                        Trace.WriteLine("Created a new foreign network customer " + value.ForeignNetworkUserID + " as customer ID " + value.TargetCustomerID.ToString());

                        CustRepo.AddForeignNetworkForCustomer(value.TargetCustomerID, value.ForeignNetworkUserID, value.ForeignNetworkType);
                    }

                    createTargetStatus = true;
                }
            }

            ChalRepo.Update(value);

            try
            {
                Activity activity = new Activity(value.ID, DateTime.UtcNow) { Type = (int)ActivityType.ActivityCreateDare, CustomerID = value.CustomerID };
                RepoFactory.GetActivityRepo().Add(activity);
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine("New Challenge Exception: " + e.ToString());
            }

            if (createTargetStatus)
            {
                // notify the receipient of the new challenge.
                CustomerNotifier.NotifyNewChallenge(value.CustomerID, value.TargetCustomerID, value.ID);
            }

            return PrepOutboundChallenge(value);
        }
 public Audience DetermineVisibility(Customer c)
 {
     return Audience.Users;
 }
        public bool LinkForeignUserToCustomer(Customer custToLink, string handle, Customer.ForeignUserTypes type)
        {
            ICustomerRepository custRepo=RepoFactory.GetCustomerRepo();
            OnboardResult res = new OnboardResult();

            if (type == Customer.ForeignUserTypes.Twitter)
            {
                if (!handle.StartsWith("@"))
                    handle = "@" + handle.ToLower();
            }

            Customer c = custRepo.GetWithForeignUserID(handle, type);
            if (c != null)
            {
                if (c.ID == custToLink.ID)
                    return true;

                if (c.Type != (int)Customer.TypeCodes.Unclaimed)
                    return false;

                try
                {
                    RepoFactory.GetChallengeRepo().MoveChallengesToCustomer(c.ID, custToLink.ID);
                    custRepo.RemoveForeignNetworkForCustomer(c.ID, handle, type);
                }
                catch (Exception e)
                {
                    System.Diagnostics.Trace.WriteLine("Onboard Exception: " + e.ToString());
                }

                custRepo.Remove(c.ID);
            }

            custRepo.AddForeignNetworkForCustomer(custToLink.ID, handle, type);
            return true;
        }