Esempio n. 1
0
        /// <summary>
        /// Updates the parent of the given category
        /// </summary>
        /// <param name="categoryId">Id of the category for which to update the parent</param>
        /// <param name="parentId">Parent Id to set</param>
        public static void UpdateParent(int categoryId, int parentId)
        {
            //GET DATABSAE REFERENCES
            Database  database = Token.Instance.Database;
            DbCommand selectCommand;

            //VERIFY THE SPECIFIED CATEGORY IS VALID
            if (parentId != 0)
            {
                selectCommand = database.GetSqlStringCommand("SELECT CategoryId FROM ac_Categories WHERE CategoryId = @categoryId");
                database.AddInParameter(selectCommand, "@categoryId", DbType.Int32, categoryId);
                object scalarResult = database.ExecuteScalar(selectCommand);
                if (scalarResult == null)
                {
                    throw new ArgumentException("This category instance has not been saved to the database.", "CategoryId");
                }
            }

            //VERIFY THE SELECTED PARENT IS VALID
            if (parentId != 0)
            {
                selectCommand = database.GetSqlStringCommand("SELECT CategoryId FROM ac_Categories WHERE CategoryId = @categoryId");
                database.AddInParameter(selectCommand, "@categoryId", DbType.Int32, parentId);
                object scalarResult = database.ExecuteScalar(selectCommand);
                if (scalarResult == null)
                {
                    throw new ArgumentException("Invalid parent category specified.", "parentId");
                }
            }

            //CHECK FOR CIRCULAR REFRENCES
            if (categoryId.Equals(parentId))
            {
                throw new ArgumentException("Specified parent category would result in a circular reference.", "parentId");
            }
            selectCommand = database.GetSqlStringCommand("SELECT COUNT(*) As ChildReferences FROM ac_CategoryParents WHERE ParentId = @categoryId AND CategoryId = @parentId");
            database.AddInParameter(selectCommand, "@categoryId", DbType.Int32, categoryId);
            database.AddInParameter(selectCommand, "@parentId", DbType.Int32, parentId);
            int childReferences = (int)database.ExecuteScalar(selectCommand);

            if (childReferences > 0)
            {
                throw new ArgumentException("Specified parent category would result in a circular reference.", "parentId");
            }

            //UPDATE CATEGORY PARENT
            DbCommand updateCommand = database.GetSqlStringCommand("UPDATE ac_Categories SET ParentId = @parentId WHERE CategoryId = @categoryId");

            database.AddInParameter(updateCommand, "@categoryId", DbType.Int32, categoryId);
            database.AddInParameter(updateCommand, "@parentId", DbType.Int32, parentId);
            database.ExecuteNonQuery(updateCommand);

            //DELETE ANY EXISTING PARENT ASSOCIATIONS
            DbCommand deleteCommand = database.GetSqlStringCommand("DELETE FROM ac_CategoryParents WHERE CategoryId = @categoryId");

            database.AddInParameter(deleteCommand, "@categoryId", DbType.Int32, categoryId);
            database.ExecuteNonQuery(deleteCommand);
            deleteCommand = database.GetSqlStringCommand("DELETE FROM ac_CatalogNodes WHERE CatalogNodeTypeId = 0 AND CatalogNodeId = @categoryId");
            database.AddInParameter(deleteCommand, "@categoryId", DbType.Int32, categoryId);
            database.ExecuteNonQuery(deleteCommand);

            //NOW INSERT MODIFIED PARENT PATH
            StringBuilder insertQuery;
            DbCommand     insertCommand;
            int           level;

            if (parentId != 0)
            {
                insertQuery = new StringBuilder();
                insertQuery.Append("INSERT INTO ac_CategoryParents (CategoryId, ParentId, ParentLevel, ParentNumber)");
                insertQuery.Append(" SELECT @categoryId, ParentId, ParentLevel, (ParentNumber + 1)");
                insertQuery.Append(" FROM ac_CategoryParents");
                insertQuery.Append(" WHERE CategoryId = @parentCategoryId;");
                insertCommand = database.GetSqlStringCommand(insertQuery.ToString());
                database.AddInParameter(insertCommand, "@categoryId", DbType.Int32, categoryId);
                database.AddInParameter(insertCommand, "@parentCategoryId", DbType.Int32, parentId);
                database.ExecuteNonQuery(insertCommand);
                //GET LEVEL OF NEW CATEGORY
                selectCommand = database.GetSqlStringCommand("SELECT (ParentLevel + 1) FROM ac_CategoryParents WHERE CategoryId = @parentCategoryId AND ParentNumber=0");
                database.AddInParameter(selectCommand, "@parentCategoryId", DbType.Int32, parentId);
                level = AlwaysConvert.ToInt(database.ExecuteScalar(selectCommand));
            }
            else
            {
                insertQuery = new StringBuilder();
                insertQuery.Append("INSERT INTO ac_CategoryParents (CategoryId, ParentId, ParentLevel, ParentNumber)");
                insertQuery.Append(" VALUES (@categoryId, 0, 0, 1)");
                insertCommand = database.GetSqlStringCommand(insertQuery.ToString());
                database.AddInParameter(insertCommand, "@categoryId", DbType.Int32, categoryId);
                database.ExecuteNonQuery(insertCommand);
                level = 1;
            }

            // NOW INSERT SELF-REFERENCING PATH
            insertQuery = new StringBuilder();
            insertQuery.Append("INSERT INTO ac_CategoryParents (CategoryId, ParentId, ParentLevel, ParentNumber)");
            insertQuery.Append(" VALUES (@categoryId, @categoryId, @level, 0);");
            insertCommand = database.GetSqlStringCommand(insertQuery.ToString());
            database.AddInParameter(insertCommand, "@categoryId", DbType.Int32, categoryId);
            database.AddInParameter(insertCommand, "@level", DbType.Int32, level);
            database.ExecuteNonQuery(insertCommand);

            //GET ORDER OF NEW CATEGORY
            selectCommand = database.GetSqlStringCommand("SELECT (MAX(OrderBy) + 1) FROM ac_CatalogNodes WHERE CategoryId = @parentCategoryId");
            database.AddInParameter(selectCommand, "@parentCategoryId", DbType.Int32, parentId);
            Int16 order = AlwaysConvert.ToInt16(database.ExecuteScalar(selectCommand));

            //ADD IN CATALOG NODE
            insertQuery = new StringBuilder();
            insertQuery.Append("INSERT INTO ac_CatalogNodes (CategoryId, CatalogNodeId, CatalogNodeTypeId, OrderBy)");
            insertQuery.Append(" VALUES (@parentCategoryId, @categoryId, 0, @order)");
            insertCommand = database.GetSqlStringCommand(insertQuery.ToString());
            database.AddInParameter(insertCommand, "@parentCategoryId", DbType.Int32, parentId);
            database.AddInParameter(insertCommand, "@categoryId", DbType.Int32, categoryId);
            database.AddInParameter(insertCommand, "@order", DbType.Int16, order);
            database.ExecuteNonQuery(insertCommand);

            // GET ANY CHILD CATEGORIES OF CURRENT CATEGORY
            List <int> catalogNodeIds = new List <int>();

            selectCommand = database.GetSqlStringCommand("SELECT CategoryId FROM ac_Categories WHERE ParentId = @categoryId");
            database.AddInParameter(selectCommand, "@categoryId", DbType.Int32, categoryId);
            using (IDataReader reader = database.ExecuteReader(selectCommand))
            {
                while (reader.Read())
                {
                    catalogNodeIds.Add(reader.GetInt32(0));
                }
                reader.Close();
            }
            foreach (int catalogNodeId in catalogNodeIds)
            {
                Category.UpdateParent(catalogNodeId, categoryId);
            }
        }
        private void Ship(bool requestTracking)
        {
            //WE HAVE TO LOOK FOR ANY ITEMS NOT BEING SHIPPED
            //BUILD A DICTIONARY OF QUANTITY TO SHIP
            bool itemFound        = false;
            bool isPartial        = false;
            bool quantityExceeded = false;
            Dictionary <int, short> quantities = new Dictionary <int, short>();

            foreach (GridViewRow row in ShipmentItems.Rows)
            {
                HiddenField hf          = (HiddenField)row.FindControl("Id");
                int         orderItemId = AlwaysConvert.ToInt(hf.Value);
                int         index       = _OrderShipment.OrderItems.IndexOf(orderItemId);
                if (index > -1)
                {
                    TextBox tb  = (TextBox)row.FindControl("Quantity");
                    short   qty = AlwaysConvert.ToInt16(tb.Text);
                    itemFound        = itemFound || (qty > 0);
                    isPartial        = isPartial || (qty < _OrderShipment.OrderItems[index].Quantity);
                    quantityExceeded = quantityExceeded || (qty > _OrderShipment.OrderItems[index].Quantity);
                    quantities.Add(orderItemId, qty);
                }
            }

            if ((itemFound) && (!quantityExceeded))
            {
                try
                {
                    // start transation to do it in single step
                    AbleContext.Current.Database.BeginTransaction();

                    //CHECK IF WE ARE NOT SHIPPING ALL OF THE ITEMS
                    if (isPartial)
                    {
                        //AT LEAST ONE ITEM MUST BE MOVED TO A NEW SHIPMENT
                        //CREATE A COPY OF THIS SHIPMENT
                        OrderShipment newShipment = _OrderShipment.Copy();
                        newShipment.Save();
                        _Order.Shipments.Add(newShipment);
                        //KEEP TRACK OF ITEMS TO REMOVE FROM THE CURRENT SHIPMENT
                        List <int> removeItems = new List <int>();
                        //LOOP THE ITEMS AND DECIDE WHICH TO PUT IN THE NEW SHIPMENT
                        foreach (OrderItem item in _OrderShipment.OrderItems)
                        {
                            int searchItemId = (AlwaysConvert.ToInt(item.ParentItemId) == 0) ? item.Id : AlwaysConvert.ToInt(item.ParentItemId);
                            if (quantities.ContainsKey(searchItemId))
                            {
                                short shipQty = quantities[searchItemId];
                                if (shipQty != item.Quantity)
                                {
                                    if (shipQty > 0)
                                    {
                                        //WE HAVE TO SPLIT THIS ITEM
                                        OrderItem newItem = OrderItem.Copy(item.Id, true);
                                        newItem.Quantity        = (short)(item.Quantity - shipQty);
                                        newItem.OrderShipmentId = newShipment.Id;
                                        newItem.Save();
                                        newShipment.OrderItems.Add(newItem);
                                        //UPDATE THE CURRENT ITEM
                                        item.Quantity = shipQty;
                                        item.Save();
                                    }
                                    else
                                    {
                                        //THIS ITEM JUST NEEDS TO BE MOVED
                                        item.OrderShipmentId = newShipment.Id;
                                        item.Save();
                                        newShipment.OrderItems.Add(item);
                                        removeItems.Add(item.Id);
                                    }
                                }
                            }
                        }
                        //REMOVE ANY ITEMS THAT WERE MOVED TO ANOTHER SHIPMENT
                        foreach (int id in removeItems)
                        {
                            int delIndex = _OrderShipment.OrderItems.IndexOf(id);
                            if (delIndex > -1)
                            {
                                _OrderShipment.OrderItems.RemoveAt(delIndex);
                            }
                        }
                    }

                    //Add the Tracking Number
                    int    shipgwId     = AlwaysConvert.ToInt(ShipGateway.SelectedValue);
                    string trackingData = AddTrackingNumber.Text.Trim();
                    if (!string.IsNullOrEmpty(trackingData))
                    {
                        TrackingNumber tnum = new TrackingNumber();
                        tnum.TrackingNumberData = trackingData;
                        tnum.ShipGatewayId      = shipgwId;
                        tnum.OrderShipmentId    = _OrderShipment.Id;
                        _OrderShipment.TrackingNumbers.Add(tnum);
                    }

                    //SHIP THE CURRENT SHIPMENT
                    _OrderShipment.Ship(requestTracking, LocaleHelper.LocalNow);

                    // end transaction
                    AbleContext.Current.Database.CommitTransaction();

                    //RETURN TO SHIPMENTS PAGE
                    Response.Redirect(CancelButton.NavigateUrl, false);
                }
                catch (Exception ex)
                {
                    AbleContext.Current.Database.RollbackTransaction();
                    Logger.Error(string.Format("An error occurred while trying to confirm shipment to provider: {0}", ex.Message), ex);

                    CustomValidator shipError = new CustomValidator();
                    shipError.Text         = "*";
                    shipError.ErrorMessage = ex.Message;
                    shipError.IsValid      = false;
                    phValidation.Controls.Add(shipError);
                }
            }
            else
            {
                CustomValidator quantityError = new CustomValidator();
                if (quantityExceeded)
                {
                    quantityError.ErrorMessage = "You cannot move more than the existing quantity.";
                }
                else
                {
                    quantityError.ErrorMessage = "You must pick at least one item to move.";
                }
                quantityError.Text    = "&nbsp;";
                quantityError.IsValid = false;
                phValidation.Controls.Add(quantityError);
            }
        }
        /// <summary>
        /// Saves this Address object to the database.
        /// </summary>
        /// <returns><b>SaveResult</b> enumeration that represents the result of the save operation.</returns>
        public virtual SaveResult Save()
        {
            if (this.IsDirty)
            {
                Database database     = Token.Instance.Database;
                bool     recordExists = true;

                if (this.AddressId == 0)
                {
                    recordExists = false;
                }

                if (recordExists)
                {
                    //verify whether record is already present
                    StringBuilder selectQuery = new StringBuilder();
                    selectQuery.Append("SELECT COUNT(*) As RecordCount FROM ac_Addresses");
                    selectQuery.Append(" WHERE AddressId = @AddressId");
                    using (DbCommand selectCommand = database.GetSqlStringCommand(selectQuery.ToString()))
                    {
                        database.AddInParameter(selectCommand, "@AddressId", System.Data.DbType.Int32, this.AddressId);
                        if ((int)database.ExecuteScalar(selectCommand) == 0)
                        {
                            recordExists = false;
                        }
                    }
                }

                int result = 0;
                if (recordExists)
                {
                    //UPDATE
                    StringBuilder updateQuery = new StringBuilder();
                    updateQuery.Append("UPDATE ac_Addresses SET ");
                    updateQuery.Append("UserId = @UserId");
                    updateQuery.Append(", Nickname = @Nickname");
                    updateQuery.Append(", FirstName = @FirstName");
                    updateQuery.Append(", LastName = @LastName");
                    updateQuery.Append(", Company = @Company");
                    updateQuery.Append(", Address1 = @Address1");
                    updateQuery.Append(", Address2 = @Address2");
                    updateQuery.Append(", City = @City");
                    updateQuery.Append(", Province = @Province");
                    updateQuery.Append(", PostalCode = @PostalCode");
                    updateQuery.Append(", CountryCode = @CountryCode");
                    updateQuery.Append(", Phone = @Phone");
                    updateQuery.Append(", Fax = @Fax");
                    updateQuery.Append(", Email = @Email");
                    updateQuery.Append(", Residence = @Residence");
                    updateQuery.Append(", Validated = @Validated");
                    updateQuery.Append(" WHERE AddressId = @AddressId");
                    using (DbCommand updateCommand = database.GetSqlStringCommand(updateQuery.ToString()))
                    {
                        database.AddInParameter(updateCommand, "@AddressId", System.Data.DbType.Int32, this.AddressId);
                        database.AddInParameter(updateCommand, "@UserId", System.Data.DbType.Int32, this.UserId);
                        database.AddInParameter(updateCommand, "@Nickname", System.Data.DbType.String, NullableData.DbNullify(this.Nickname));
                        database.AddInParameter(updateCommand, "@FirstName", System.Data.DbType.String, NullableData.DbNullify(this.FirstName));
                        database.AddInParameter(updateCommand, "@LastName", System.Data.DbType.String, NullableData.DbNullify(this.LastName));
                        database.AddInParameter(updateCommand, "@Company", System.Data.DbType.String, NullableData.DbNullify(this.Company));
                        database.AddInParameter(updateCommand, "@Address1", System.Data.DbType.String, NullableData.DbNullify(this.Address1));
                        database.AddInParameter(updateCommand, "@Address2", System.Data.DbType.String, NullableData.DbNullify(this.Address2));
                        database.AddInParameter(updateCommand, "@City", System.Data.DbType.String, NullableData.DbNullify(this.City));
                        database.AddInParameter(updateCommand, "@Province", System.Data.DbType.String, NullableData.DbNullify(this.Province));
                        database.AddInParameter(updateCommand, "@PostalCode", System.Data.DbType.String, NullableData.DbNullify(this.PostalCode));
                        database.AddInParameter(updateCommand, "@CountryCode", System.Data.DbType.String, NullableData.DbNullify(this.CountryCode));
                        database.AddInParameter(updateCommand, "@Phone", System.Data.DbType.String, NullableData.DbNullify(this.Phone));
                        database.AddInParameter(updateCommand, "@Fax", System.Data.DbType.String, NullableData.DbNullify(this.Fax));
                        database.AddInParameter(updateCommand, "@Email", System.Data.DbType.String, NullableData.DbNullify(this.Email));
                        database.AddInParameter(updateCommand, "@Residence", System.Data.DbType.Boolean, this.Residence);
                        database.AddInParameter(updateCommand, "@Validated", System.Data.DbType.Boolean, this.Validated);
                        //RESULT IS NUMBER OF RECORDS AFFECTED
                        result = database.ExecuteNonQuery(updateCommand);
                    }
                }
                else
                {
                    //INSERT
                    StringBuilder insertQuery = new StringBuilder();
                    insertQuery.Append("INSERT INTO ac_Addresses (UserId, Nickname, FirstName, LastName, Company, Address1, Address2, City, Province, PostalCode, CountryCode, Phone, Fax, Email, Residence, Validated)");
                    insertQuery.Append(" VALUES (@UserId, @Nickname, @FirstName, @LastName, @Company, @Address1, @Address2, @City, @Province, @PostalCode, @CountryCode, @Phone, @Fax, @Email, @Residence, @Validated)");
                    insertQuery.Append("; SELECT Scope_Identity()");
                    using (DbCommand insertCommand = database.GetSqlStringCommand(insertQuery.ToString()))
                    {
                        database.AddInParameter(insertCommand, "@AddressId", System.Data.DbType.Int32, this.AddressId);
                        database.AddInParameter(insertCommand, "@UserId", System.Data.DbType.Int32, this.UserId);
                        database.AddInParameter(insertCommand, "@Nickname", System.Data.DbType.String, NullableData.DbNullify(this.Nickname));
                        database.AddInParameter(insertCommand, "@FirstName", System.Data.DbType.String, NullableData.DbNullify(this.FirstName));
                        database.AddInParameter(insertCommand, "@LastName", System.Data.DbType.String, NullableData.DbNullify(this.LastName));
                        database.AddInParameter(insertCommand, "@Company", System.Data.DbType.String, NullableData.DbNullify(this.Company));
                        database.AddInParameter(insertCommand, "@Address1", System.Data.DbType.String, NullableData.DbNullify(this.Address1));
                        database.AddInParameter(insertCommand, "@Address2", System.Data.DbType.String, NullableData.DbNullify(this.Address2));
                        database.AddInParameter(insertCommand, "@City", System.Data.DbType.String, NullableData.DbNullify(this.City));
                        database.AddInParameter(insertCommand, "@Province", System.Data.DbType.String, NullableData.DbNullify(this.Province));
                        database.AddInParameter(insertCommand, "@PostalCode", System.Data.DbType.String, NullableData.DbNullify(this.PostalCode));
                        database.AddInParameter(insertCommand, "@CountryCode", System.Data.DbType.String, NullableData.DbNullify(this.CountryCode));
                        database.AddInParameter(insertCommand, "@Phone", System.Data.DbType.String, NullableData.DbNullify(this.Phone));
                        database.AddInParameter(insertCommand, "@Fax", System.Data.DbType.String, NullableData.DbNullify(this.Fax));
                        database.AddInParameter(insertCommand, "@Email", System.Data.DbType.String, NullableData.DbNullify(this.Email));
                        database.AddInParameter(insertCommand, "@Residence", System.Data.DbType.Boolean, this.Residence);
                        database.AddInParameter(insertCommand, "@Validated", System.Data.DbType.Boolean, this.Validated);
                        //RESULT IS NEW IDENTITY;
                        result          = AlwaysConvert.ToInt(database.ExecuteScalar(insertCommand));
                        this._AddressId = result;
                    }
                }
                this.SaveChildren();

                //OBJECT IS DIRTY IF NO RECORDS WERE UPDATED OR INSERTED
                this.IsDirty = (result == 0);
                if (this.IsDirty)
                {
                    return(SaveResult.Failed);
                }
                else
                {
                    return(recordExists ? SaveResult.RecordUpdated : SaveResult.RecordInserted);
                }
            }

            //SAVE IS SUCCESSFUL IF OBJECT IS NOT DIRTY
            return(SaveResult.NotDirty);
        }
Esempio n. 4
0
        /// <summary>
        /// Saves this Transaction object to the database.
        /// </summary>
        /// <returns><b>SaveResult</b> enumeration that represents the result of the save operation.</returns>
        public virtual SaveResult Save()
        {
            if (this.IsDirty)
            {
                Database database     = Token.Instance.Database;
                bool     recordExists = true;

                if (this.TransactionId == 0)
                {
                    recordExists = false;
                }

                //SET DEFAULT FOR DATE FIELD
                if (this.TransactionDate == System.DateTime.MinValue)
                {
                    this.TransactionDate = LocaleHelper.LocalNow;
                }

                if (recordExists)
                {
                    //verify whether record is already present
                    StringBuilder selectQuery = new StringBuilder();
                    selectQuery.Append("SELECT COUNT(*) As RecordCount FROM ac_Transactions");
                    selectQuery.Append(" WHERE TransactionId = @TransactionId");
                    using (DbCommand selectCommand = database.GetSqlStringCommand(selectQuery.ToString()))
                    {
                        database.AddInParameter(selectCommand, "@TransactionId", System.Data.DbType.Int32, this.TransactionId);
                        if ((int)database.ExecuteScalar(selectCommand) == 0)
                        {
                            recordExists = false;
                        }
                    }
                }

                int result = 0;
                if (recordExists)
                {
                    //UPDATE
                    StringBuilder updateQuery = new StringBuilder();
                    updateQuery.Append("UPDATE ac_Transactions SET ");
                    updateQuery.Append("TransactionTypeId = @TransactionTypeId");
                    updateQuery.Append(", PaymentId = @PaymentId");
                    updateQuery.Append(", PaymentGatewayId = @PaymentGatewayId");
                    updateQuery.Append(", ProviderTransactionId = @ProviderTransactionId");
                    updateQuery.Append(", TransactionDate = @TransactionDate");
                    updateQuery.Append(", Amount = @Amount");
                    updateQuery.Append(", TransactionStatusId = @TransactionStatusId");
                    updateQuery.Append(", ResponseCode = @ResponseCode");
                    updateQuery.Append(", ResponseMessage = @ResponseMessage");
                    updateQuery.Append(", AuthorizationCode = @AuthorizationCode");
                    updateQuery.Append(", AVSResultCode = @AVSResultCode");
                    updateQuery.Append(", CVVResultCode = @CVVResultCode");
                    updateQuery.Append(", CAVResultCode = @CAVResultCode");
                    updateQuery.Append(", RemoteIP = @RemoteIP");
                    updateQuery.Append(", Referrer = @Referrer");
                    updateQuery.Append(", AdditionalData = @AdditionalData");
                    updateQuery.Append(" WHERE TransactionId = @TransactionId");
                    using (DbCommand updateCommand = database.GetSqlStringCommand(updateQuery.ToString()))
                    {
                        database.AddInParameter(updateCommand, "@TransactionId", System.Data.DbType.Int32, this.TransactionId);
                        database.AddInParameter(updateCommand, "@TransactionTypeId", System.Data.DbType.Int16, this.TransactionTypeId);
                        database.AddInParameter(updateCommand, "@PaymentId", System.Data.DbType.Int32, this.PaymentId);
                        database.AddInParameter(updateCommand, "@PaymentGatewayId", System.Data.DbType.Int32, NullableData.DbNullify(this.PaymentGatewayId));
                        database.AddInParameter(updateCommand, "@ProviderTransactionId", System.Data.DbType.String, NullableData.DbNullify(this.ProviderTransactionId));
                        database.AddInParameter(updateCommand, "@TransactionDate", System.Data.DbType.DateTime, LocaleHelper.FromLocalTime(this.TransactionDate));
                        database.AddInParameter(updateCommand, "@Amount", System.Data.DbType.Decimal, this.Amount);
                        database.AddInParameter(updateCommand, "@TransactionStatusId", System.Data.DbType.Int16, this.TransactionStatusId);
                        database.AddInParameter(updateCommand, "@ResponseCode", System.Data.DbType.String, NullableData.DbNullify(this.ResponseCode));
                        database.AddInParameter(updateCommand, "@ResponseMessage", System.Data.DbType.String, NullableData.DbNullify(this.ResponseMessage));
                        database.AddInParameter(updateCommand, "@AuthorizationCode", System.Data.DbType.String, NullableData.DbNullify(this.AuthorizationCode));
                        database.AddInParameter(updateCommand, "@AVSResultCode", System.Data.DbType.String, NullableData.DbNullify(this.AVSResultCode));
                        database.AddInParameter(updateCommand, "@CVVResultCode", System.Data.DbType.String, NullableData.DbNullify(this.CVVResultCode));
                        database.AddInParameter(updateCommand, "@CAVResultCode", System.Data.DbType.String, NullableData.DbNullify(this.CAVResultCode));
                        database.AddInParameter(updateCommand, "@RemoteIP", System.Data.DbType.String, NullableData.DbNullify(this.RemoteIP));
                        database.AddInParameter(updateCommand, "@Referrer", System.Data.DbType.String, NullableData.DbNullify(this.Referrer));
                        database.AddInParameter(updateCommand, "@AdditionalData", System.Data.DbType.String, NullableData.DbNullify(this.AdditionalData));
                        //RESULT IS NUMBER OF RECORDS AFFECTED
                        result = database.ExecuteNonQuery(updateCommand);
                    }
                }
                else
                {
                    //INSERT
                    StringBuilder insertQuery = new StringBuilder();
                    insertQuery.Append("INSERT INTO ac_Transactions (TransactionTypeId, PaymentId, PaymentGatewayId, ProviderTransactionId, TransactionDate, Amount, TransactionStatusId, ResponseCode, ResponseMessage, AuthorizationCode, AVSResultCode, CVVResultCode, CAVResultCode, RemoteIP, Referrer, AdditionalData)");
                    insertQuery.Append(" VALUES (@TransactionTypeId, @PaymentId, @PaymentGatewayId, @ProviderTransactionId, @TransactionDate, @Amount, @TransactionStatusId, @ResponseCode, @ResponseMessage, @AuthorizationCode, @AVSResultCode, @CVVResultCode, @CAVResultCode, @RemoteIP, @Referrer, @AdditionalData)");
                    insertQuery.Append("; SELECT Scope_Identity()");
                    using (DbCommand insertCommand = database.GetSqlStringCommand(insertQuery.ToString()))
                    {
                        database.AddInParameter(insertCommand, "@TransactionId", System.Data.DbType.Int32, this.TransactionId);
                        database.AddInParameter(insertCommand, "@TransactionTypeId", System.Data.DbType.Int16, this.TransactionTypeId);
                        database.AddInParameter(insertCommand, "@PaymentId", System.Data.DbType.Int32, this.PaymentId);
                        database.AddInParameter(insertCommand, "@PaymentGatewayId", System.Data.DbType.Int32, NullableData.DbNullify(this.PaymentGatewayId));
                        database.AddInParameter(insertCommand, "@ProviderTransactionId", System.Data.DbType.String, NullableData.DbNullify(this.ProviderTransactionId));
                        database.AddInParameter(insertCommand, "@TransactionDate", System.Data.DbType.DateTime, LocaleHelper.FromLocalTime(this.TransactionDate));
                        database.AddInParameter(insertCommand, "@Amount", System.Data.DbType.Decimal, this.Amount);
                        database.AddInParameter(insertCommand, "@TransactionStatusId", System.Data.DbType.Int16, this.TransactionStatusId);
                        database.AddInParameter(insertCommand, "@ResponseCode", System.Data.DbType.String, NullableData.DbNullify(this.ResponseCode));
                        database.AddInParameter(insertCommand, "@ResponseMessage", System.Data.DbType.String, NullableData.DbNullify(this.ResponseMessage));
                        database.AddInParameter(insertCommand, "@AuthorizationCode", System.Data.DbType.String, NullableData.DbNullify(this.AuthorizationCode));
                        database.AddInParameter(insertCommand, "@AVSResultCode", System.Data.DbType.String, NullableData.DbNullify(this.AVSResultCode));
                        database.AddInParameter(insertCommand, "@CVVResultCode", System.Data.DbType.String, NullableData.DbNullify(this.CVVResultCode));
                        database.AddInParameter(insertCommand, "@CAVResultCode", System.Data.DbType.String, NullableData.DbNullify(this.CAVResultCode));
                        database.AddInParameter(insertCommand, "@RemoteIP", System.Data.DbType.String, NullableData.DbNullify(this.RemoteIP));
                        database.AddInParameter(insertCommand, "@Referrer", System.Data.DbType.String, NullableData.DbNullify(this.Referrer));
                        database.AddInParameter(insertCommand, "@AdditionalData", System.Data.DbType.String, NullableData.DbNullify(this.AdditionalData));
                        //RESULT IS NEW IDENTITY;
                        result = AlwaysConvert.ToInt(database.ExecuteScalar(insertCommand));
                        this._TransactionId = result;
                    }
                }
                this.SaveChildren();

                //OBJECT IS DIRTY IF NO RECORDS WERE UPDATED OR INSERTED
                this.IsDirty = (result == 0);
                if (this.IsDirty)
                {
                    return(SaveResult.Failed);
                }
                else
                {
                    return(recordExists ? SaveResult.RecordUpdated : SaveResult.RecordInserted);
                }
            }

            //SAVE IS SUCCESSFUL IF OBJECT IS NOT DIRTY
            return(SaveResult.NotDirty);
        }
Esempio n. 5
0
        private void BindData()
        {
            // get database name
            SqlConnection con    = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ConnectionString);
            string        dbName = con.Database;

            // build query
            StringBuilder queryStr = new StringBuilder();

            queryStr.Append("DECLARE @SPWHO2 TABLE (SPID VARCHAR(1000), [Status] VARCHAR(1000) NULL, [Login] VARCHAR(1000) NULL");
            queryStr.Append(", HostName VARCHAR(1000) NULL, BlkBy VARCHAR(1000) NULL, DBName VARCHAR(1000) NULL, Command VARCHAR(1000) NULL");
            queryStr.Append(", CPUTime VARCHAR(1000) NULL, DiskIO VARCHAR(1000) NULL, LastBatch VARCHAR(1000) NULL, ProgramName VARCHAR(1000) NULL");
            queryStr.Append(", SPID2 VARCHAR(1000) NULL, Request VARCHAR(1000) NULL) ");
            queryStr.Append("INSERT INTO @SPWHO2 EXEC sp_who2");
            if (ActiveOnly.Checked)
            {
                queryStr.Append(" 'Active' ");
            }

            queryStr.Append(" SELECT * FROM @SPWHO2 WHERE DBName = :dbName");

            var nhQuery = NHibernateHelper.CreateSQLQuery(queryStr.ToString())
                          .SetString("dbName", dbName);

            // execute query
            var results = nhQuery.List();

            // parse results
            IList <RptData> finalData = new List <RptData>();

            foreach (object[] resultRow in results)
            {
                RptData row = new RptData();
                row.Spid        = (string)resultRow[0];
                row.Status      = (string)resultRow[1];
                row.Login       = (string)resultRow[2];
                row.HostName    = (string)resultRow[3];
                row.BlkBy       = (string)resultRow[4];
                row.DbName      = (string)resultRow[5];
                row.Command     = (string)resultRow[6];
                row.CPUTime     = (string)resultRow[7];
                row.DiskIO      = (string)resultRow[8];
                row.LastBatch   = (string)resultRow[9];
                row.ProgramName = (string)resultRow[10];
                row.SPID2       = (string)resultRow[11];
                row.Request     = (string)resultRow[12];
                finalData.Add(row);
            }

            ConnectionsGrid.DataSource = finalData;
            ConnectionsGrid.DataBind();

            // summarize data
            ConnectionsCount.Text = finalData.Count.ToString();

            if (Session["LastCount"] != null)
            {
                int lastCount = AlwaysConvert.ToInt(Session["LastCount"], 0);
                int diff      = finalData.Count - lastCount;
                Changed.Text = diff.ToString();
            }
            else
            {
                Changed.Text = "n/a";
            }

            Session["LastCount"] = finalData.Count.ToString();
        }
Esempio n. 6
0
        /// <summary>
        /// Saves this Category object to the database.
        /// </summary>
        /// <returns><b>SaveResult</b> enumeration that represents the result of the save operation.</returns>
        protected SaveResult BaseSave()
        {
            if (this.IsDirty)
            {
                Database database     = Token.Instance.Database;
                bool     recordExists = true;

                //SET EMPTY STOREID TO CURRENT CONTEXT
                if (this.StoreId == 0)
                {
                    this.StoreId = Token.Instance.StoreId;
                }
                if (this.CategoryId == 0)
                {
                    recordExists = false;
                }

                if (recordExists)
                {
                    //verify whether record is already present
                    StringBuilder selectQuery = new StringBuilder();
                    selectQuery.Append("SELECT COUNT(*) As RecordCount FROM ac_Categories");
                    selectQuery.Append(" WHERE CategoryId = @CategoryId");
                    using (DbCommand selectCommand = database.GetSqlStringCommand(selectQuery.ToString()))
                    {
                        database.AddInParameter(selectCommand, "@CategoryId", System.Data.DbType.Int32, this.CategoryId);
                        if ((int)database.ExecuteScalar(selectCommand) == 0)
                        {
                            recordExists = false;
                        }
                    }
                }

                int result = 0;
                if (recordExists)
                {
                    //UPDATE
                    StringBuilder updateQuery = new StringBuilder();
                    updateQuery.Append("UPDATE ac_Categories SET ");
                    updateQuery.Append("StoreId = @StoreId");
                    updateQuery.Append(", ParentId = @ParentId");
                    updateQuery.Append(", Name = @Name");
                    updateQuery.Append(", Summary = @Summary");
                    updateQuery.Append(", Description = @Description");
                    updateQuery.Append(", ThumbnailUrl = @ThumbnailUrl");
                    updateQuery.Append(", ThumbnailAltText = @ThumbnailAltText");
                    updateQuery.Append(", DisplayPage = @DisplayPage");
                    updateQuery.Append(", Theme = @Theme");
                    updateQuery.Append(", HtmlHead = @HtmlHead");
                    updateQuery.Append(", VisibilityId = @VisibilityId");
                    updateQuery.Append(" WHERE CategoryId = @CategoryId");
                    using (DbCommand updateCommand = database.GetSqlStringCommand(updateQuery.ToString()))
                    {
                        database.AddInParameter(updateCommand, "@CategoryId", System.Data.DbType.Int32, this.CategoryId);
                        database.AddInParameter(updateCommand, "@StoreId", System.Data.DbType.Int32, this.StoreId);
                        database.AddInParameter(updateCommand, "@ParentId", System.Data.DbType.Int32, this.ParentId);
                        database.AddInParameter(updateCommand, "@Name", System.Data.DbType.String, this.Name);
                        database.AddInParameter(updateCommand, "@Summary", System.Data.DbType.String, NullableData.DbNullify(this.Summary));
                        database.AddInParameter(updateCommand, "@Description", System.Data.DbType.String, NullableData.DbNullify(this.Description));
                        database.AddInParameter(updateCommand, "@ThumbnailUrl", System.Data.DbType.String, NullableData.DbNullify(this.ThumbnailUrl));
                        database.AddInParameter(updateCommand, "@ThumbnailAltText", System.Data.DbType.String, NullableData.DbNullify(_ThumbnailAltText));
                        database.AddInParameter(updateCommand, "@DisplayPage", System.Data.DbType.String, NullableData.DbNullify(this.DisplayPage));
                        database.AddInParameter(updateCommand, "@Theme", System.Data.DbType.String, NullableData.DbNullify(this.Theme));
                        database.AddInParameter(updateCommand, "@HtmlHead", System.Data.DbType.String, NullableData.DbNullify(this.HtmlHead));
                        database.AddInParameter(updateCommand, "@VisibilityId", System.Data.DbType.Byte, this.VisibilityId);
                        //RESULT IS NUMBER OF RECORDS AFFECTED
                        result = database.ExecuteNonQuery(updateCommand);
                    }
                }
                else
                {
                    //INSERT
                    StringBuilder insertQuery = new StringBuilder();
                    insertQuery.Append("INSERT INTO ac_Categories (StoreId, ParentId, Name, Summary, Description, ThumbnailUrl, ThumbnailAltText, DisplayPage, Theme, HtmlHead, VisibilityId)");
                    insertQuery.Append(" VALUES (@StoreId, @ParentId, @Name, @Summary, @Description, @ThumbnailUrl, @ThumbnailAltText, @DisplayPage, @Theme, @HtmlHead, @VisibilityId)");
                    insertQuery.Append("; SELECT Scope_Identity()");
                    using (DbCommand insertCommand = database.GetSqlStringCommand(insertQuery.ToString()))
                    {
                        database.AddInParameter(insertCommand, "@CategoryId", System.Data.DbType.Int32, this.CategoryId);
                        database.AddInParameter(insertCommand, "@StoreId", System.Data.DbType.Int32, this.StoreId);
                        database.AddInParameter(insertCommand, "@ParentId", System.Data.DbType.Int32, this.ParentId);
                        database.AddInParameter(insertCommand, "@Name", System.Data.DbType.String, this.Name);
                        database.AddInParameter(insertCommand, "@Summary", System.Data.DbType.String, NullableData.DbNullify(this.Summary));
                        database.AddInParameter(insertCommand, "@Description", System.Data.DbType.String, NullableData.DbNullify(this.Description));
                        database.AddInParameter(insertCommand, "@ThumbnailUrl", System.Data.DbType.String, NullableData.DbNullify(this.ThumbnailUrl));
                        database.AddInParameter(insertCommand, "@ThumbnailAltText", System.Data.DbType.String, NullableData.DbNullify(_ThumbnailAltText));
                        database.AddInParameter(insertCommand, "@DisplayPage", System.Data.DbType.String, NullableData.DbNullify(this.DisplayPage));
                        database.AddInParameter(insertCommand, "@Theme", System.Data.DbType.String, NullableData.DbNullify(this.Theme));
                        database.AddInParameter(insertCommand, "@HtmlHead", System.Data.DbType.String, NullableData.DbNullify(this.HtmlHead));
                        database.AddInParameter(insertCommand, "@VisibilityId", System.Data.DbType.Byte, this.VisibilityId);
                        //RESULT IS NEW IDENTITY;
                        result           = AlwaysConvert.ToInt(database.ExecuteScalar(insertCommand));
                        this._CategoryId = result;
                    }
                }
                this.SaveChildren();

                //OBJECT IS DIRTY IF NO RECORDS WERE UPDATED OR INSERTED
                this.IsDirty = (result == 0);
                if (this.IsDirty)
                {
                    return(SaveResult.Failed);
                }
                else
                {
                    return(recordExists ? SaveResult.RecordUpdated : SaveResult.RecordInserted);
                }
            }

            //SAVE IS SUCCESSFUL IF OBJECT IS NOT DIRTY
            return(SaveResult.NotDirty);
        }
        public override void Initialize(int ShipGatewayId, Dictionary <string, string> ConfigurationData)
        {
            base.Initialize(ShipGatewayId, ConfigurationData);
            //INITIALIZE MY FIELDS
            if (ConfigurationData.ContainsKey("UserID"))
            {
                UserID = ConfigurationData["UserID"];
            }
            if (ConfigurationData.ContainsKey("Password"))
            {
                Password = ConfigurationData["Password"];
            }
            if (ConfigurationData.ContainsKey("EnablePackageBreakup"))
            {
                EnablePackageBreakup = AlwaysConvert.ToBool(ConfigurationData["EnablePackageBreakup"], true);
            }
            if (ConfigurationData.ContainsKey("AccountNumber"))
            {
                AccountNumber = ConfigurationData["AccountNumber"];
            }
            if (ConfigurationData.ContainsKey("ShippingKey"))
            {
                ShippingKey = ConfigurationData["ShippingKey"];
            }
            if (ConfigurationData.ContainsKey("DaysToShip"))
            {
                DaysToShip = AlwaysConvert.ToInt(ConfigurationData["DaysToShip"], 0);
            }
            if (ConfigurationData.ContainsKey("UseTestMode"))
            {
                UseTestMode = AlwaysConvert.ToBool(ConfigurationData["UseTestMode"], false);
            }
            if (ConfigurationData.ContainsKey("AccountActive"))
            {
                AccountActive = AlwaysConvert.ToBool(ConfigurationData["AccountActive"], false);
            }
            if (ConfigurationData.ContainsKey("TestModeUrl"))
            {
                TestModeUrl = ConfigurationData["TestModeUrl"];
            }
            if (ConfigurationData.ContainsKey("LiveModeUrl"))
            {
                LiveModeUrl = ConfigurationData["LiveModeUrl"];
            }
            if (ConfigurationData.ContainsKey("TrackingUrl"))
            {
                TrackingUrl = ConfigurationData["TrackingUrl"];
            }

            if (ConfigurationData.ContainsKey("DOSFlag"))
            {
                DOSFlag = AlwaysConvert.ToBool(ConfigurationData["DOSFlag"], false);
            }
            if (ConfigurationData.ContainsKey("DutiableFlag"))
            {
                DutiableFlag = AlwaysConvert.ToBool(ConfigurationData["DutiableFlag"], false);
            }
            if (ConfigurationData.ContainsKey("CustomsValueMultiplier"))
            {
                CustomsValueMultiplier = AlwaysConvert.ToDecimal(ConfigurationData["CustomsValueMultiplier"], 1);
            }
            if (ConfigurationData.ContainsKey("CommerceLicensed"))
            {
                CommerceLicensed = AlwaysConvert.ToBool(ConfigurationData["CommerceLicensed"], false);
            }
            if (ConfigurationData.ContainsKey("FilingType"))
            {
                FilingType = (FilingTypeFlags)AlwaysConvert.ToEnum(typeof(FilingTypeFlags), ConfigurationData["FilingType"], FilingTypeFlags.ITN, true);
            }
            if (ConfigurationData.ContainsKey("FTRExemptionCode"))
            {
                FTRExemptionCode = ConfigurationData["FTRExemptionCode"];
            }
            if (ConfigurationData.ContainsKey("ITNNumber"))
            {
                ITNNumber = ConfigurationData["ITNNumber"];
            }
            if (ConfigurationData.ContainsKey("EINCode"))
            {
                EINCode = ConfigurationData["EINCode"];
            }

            if (ConfigurationData.ContainsKey("MinPackageWeight"))
            {
                MinPackageWeight = AlwaysConvert.ToDecimal(ConfigurationData["MinPackageWeight"], (decimal)MinPackageWeight);
            }
            if (ConfigurationData.ContainsKey("MaxPackageWeight"))
            {
                MaxPackageWeight = AlwaysConvert.ToDecimal(ConfigurationData["MaxPackageWeight"], (decimal)MaxPackageWeight);
            }
        }
Esempio n. 8
0
        protected void CreditCardButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid && CustomValidation())
            {
                // CREATE THE PAYMENT OBJECT
                Payment payment = GetPayment();

                // PROCESS CHECKING OUT EVENT
                bool checkOut = true;
                if (CheckingOut != null)
                {
                    CheckingOutEventArgs c = new CheckingOutEventArgs(payment);
                    CheckingOut(this, c);
                    checkOut = !c.Cancel;
                }

                if (checkOut)
                {
                    // CONTINUE TO PROCESS THE CHECKOUT
                    Basket           basket           = AbleContext.Current.User.Basket;
                    ICheckoutService checkoutService  = AbleContext.Resolve <ICheckoutService>();
                    CheckoutRequest  checkoutRequest  = new CheckoutRequest(basket, payment);
                    CheckoutResponse checkoutResponse = checkoutService.ExecuteCheckout(checkoutRequest);
                    if (checkoutResponse.Success)
                    {
                        if (trSaveCard.Visible && SaveCard.Checked)
                        {
                            AccountDataDictionary cardDetails = new AccountDataDictionary();
                            cardDetails["AccountName"]     = CardName.Text.Trim();
                            cardDetails["AccountNumber"]   = CardNumber.Text.Trim();
                            cardDetails["ExpirationMonth"] = ExpirationMonth.SelectedItem.Value;
                            cardDetails["ExpirationYear"]  = ExpirationYear.SelectedItem.Value;
                            cardDetails["SecurityCode"]    = SecurityCode.Text.Trim();
                            PaymentMethod         method  = PaymentMethodDataSource.Load(AlwaysConvert.ToInt(CardType.SelectedValue));
                            PaymentGateway        gateway = method.PaymentGateway;
                            PaymentInstrumentData instr   = PaymentInstrumentData.CreateInstance(cardDetails, method.PaymentInstrumentType, null);
                            if (gateway != null)
                            {
                                var    provider          = gateway.GetInstance();
                                string customerProfileId = string.Empty;
                                var    profileResult     = _user.PaymentProfiles.Where(p => p.GatewayIdentifier == gateway.ClassId)
                                                           .GroupBy(p => p.CustomerProfileId)
                                                           .Take(1)
                                                           .Select(g => new { CustomerProfileId = g.Key })
                                                           .SingleOrDefault();

                                if (profileResult != null && !string.IsNullOrEmpty(profileResult.CustomerProfileId))
                                {
                                    customerProfileId = profileResult.CustomerProfileId;
                                }

                                if (string.IsNullOrEmpty(customerProfileId))
                                {
                                    try
                                    {
                                        var rsp = provider.DoCreateCustomerProfile(new CommerceBuilder.Payments.Providers.CreateCustomerProfileRequest(_user));
                                        if (rsp.Successful)
                                        {
                                            customerProfileId = rsp.CustomerProfileId;
                                        }
                                        else if (rsp.ResponseCode == "E00039")
                                        {
                                            var match = Regex.Match(rsp.ResponseMessage, @"\d+", RegexOptions.CultureInvariant);
                                            if (match.Success)
                                            {
                                                customerProfileId = match.Value;
                                            }
                                            else
                                            {
                                                Logger.Error(rsp.ResponseMessage);
                                            }
                                        }
                                        else
                                        {
                                            Logger.Error(rsp.ResponseMessage);
                                        }
                                    }
                                    catch (Exception exp)
                                    {
                                        Logger.Error(exp.Message);
                                    }
                                }

                                try
                                {
                                    var rsp = provider.DoCreatePaymentProfile(new CommerceBuilder.Payments.Providers.CreatePaymentProfileRequest(_user, instr, customerProfileId)
                                    {
                                        ValidateProfile = true
                                    });
                                    if (rsp.Successful)
                                    {
                                        GatewayPaymentProfile gwprofile = new GatewayPaymentProfile();
                                        gwprofile.NameOnCard        = CardName.Text.Trim();;
                                        gwprofile.Expiry            = Misc.GetStartOfDate(new DateTime(AlwaysConvert.ToInt(ExpirationYear.SelectedItem.Value), AlwaysConvert.ToInt(ExpirationMonth.SelectedItem.Value), 1));
                                        gwprofile.CustomerProfileId = customerProfileId;
                                        gwprofile.PaymentProfileId  = rsp.PaymentProfileId;
                                        gwprofile.ReferenceNumber   = StringHelper.MakeReferenceNumber(cardDetails["AccountNumber"]);
                                        gwprofile.User              = _user;
                                        gwprofile.InstrumentType    = instr.InstrumentType;
                                        gwprofile.PaymentMethodName = method.Name;
                                        gwprofile.GatewayIdentifier = gateway.ClassId;
                                        gwprofile.Save();
                                        CardName.Text   = string.Empty;
                                        CardNumber.Text = string.Empty;
                                        ExpirationMonth.SelectedIndex = 0;
                                        ExpirationYear.SelectedIndex  = 0;
                                    }
                                }
                                catch (Exception exp)
                                {
                                    Logger.Error(exp.Message);
                                }
                            }
                        }

                        if (CheckedOut != null)
                        {
                            CheckedOut(this, new CheckedOutEventArgs(checkoutResponse));
                        }
                        Response.Redirect(AbleCommerce.Code.NavigationHelper.GetReceiptUrl(checkoutResponse.Order.OrderNumber));
                    }
                    else
                    {
                        IList <string> warningMessages = checkoutResponse.WarningMessages;
                        if (warningMessages.Count == 0)
                        {
                            warningMessages.Add("The order could not be submitted at this time.  Please try again later or contact us for assistance.");
                        }
                        if (CheckedOut != null)
                        {
                            CheckedOut(this, new CheckedOutEventArgs(checkoutResponse));
                        }
                    }
                }
            }
        }
        protected BasketItem CreateBasketItem()
        {
            //GET THE PRODUCT ID
            int     productId = AlwaysConvert.ToInt(AddProductId.Value);
            Product product   = ProductDataSource.Load(productId);

            if (product == null)
            {
                return(null);
            }
            //GET THE QUANTITY
            short tempQuantity = AlwaysConvert.ToInt16(AddProductQuantity.Text);

            if (tempQuantity < 1)
            {
                return(null);
            }
            //RECALCULATE SELECTED KIT OPTIONS
            GetSelectedKitOptions(product);
            // DETERMINE THE OPTION LIST
            string optionList = ProductVariantDataSource.GetOptionList(productId, _SelectedOptions, false);

            //CREATE THE BASKET ITEM WITH GIVEN OPTIONS
            bool       calculateOneTimePrice = AlwaysConvert.ToBool(OptionalSubscription.SelectedValue, false);
            BasketItem basketItem            = BasketItemDataSource.CreateForProduct(productId, tempQuantity, optionList, AlwaysConvert.ToList(",", _SelectedKitProducts), _UserId, calculateOneTimePrice);

            if (basketItem != null)
            {
                //BASKET ID
                basketItem.BasketId = _Basket.Id;

                // PRODUCT PRICE FOR VARIABLE PRICE PRODUCT
                if (product.UseVariablePrice && !product.IsSubscription && !product.IsKit)
                {
                    basketItem.Price = AlwaysConvert.ToDecimal(AddProductVariablePrice.Text);
                }
                else
                {
                    basketItem.Price = AlwaysConvert.ToDecimal(AddProductPrice.Text);
                }

                if (product.IsSubscription)
                {
                    if (product.SubscriptionPlan.IsOptional)
                    {
                        basketItem.IsSubscription = !calculateOneTimePrice;
                    }
                    else
                    {
                        basketItem.IsSubscription = true;
                    }

                    if (basketItem.IsSubscription && product.SubscriptionPlan.IsRecurring)
                    {
                        basketItem.Frequency     = product.SubscriptionPlan.PaymentFrequencyType == PaymentFrequencyType.Optional ? AlwaysConvert.ToInt16(AutoDeliveryInterval.SelectedValue) : product.SubscriptionPlan.PaymentFrequency;
                        basketItem.FrequencyUnit = product.SubscriptionPlan.PaymentFrequencyUnit;
                    }
                    else if (basketItem.IsSubscription)
                    {
                        basketItem.Frequency     = product.SubscriptionPlan.PaymentFrequency;
                        basketItem.FrequencyUnit = product.SubscriptionPlan.PaymentFrequencyUnit;
                    }
                }


                // COLLECT ANY ADDITIONAL INPUTS
                AbleCommerce.Code.ProductHelper.CollectProductTemplateInput(basketItem, this);
            }
            return(basketItem);
        }
Esempio n. 10
0
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            // CHECK IF PAGE IS VALID
            if (Page.IsValid)
            {
                // MAKE SURE PASSWORD VALIDATES AGAINST POLICY
                if (ValidatePassword())
                {
                    // ATTEMPT TO CREATE THE USER
                    MembershipCreateStatus status;
                    User newUser = UserDataSource.CreateUser(AddEmail.Text, AddEmail.Text, AddPassword.Text, string.Empty, string.Empty, true, 0, out status);
                    if (status == MembershipCreateStatus.Success)
                    {
                        // FORCE PASSWORD EXPIRATION
                        newUser.Passwords[0].ForceExpiration = ForceExpiration.Checked;
                        newUser.Passwords[0].Save();

                        // ASSIGN GROUPS TO NEW USER
                        IList <Group> availableGroups = SecurityUtility.GetManagableGroups();
                        int           groupId         = AlwaysConvert.ToInt(AddGroup.SelectedValue);
                        if (groupId > 0)
                        {
                            int index = availableGroups.IndexOf(groupId);
                            if (groupId > -1)
                            {
                                // ADD THE GROUP ASSOCIATION FOR THE NEW USER
                                newUser.UserGroups.Add(new UserGroup(newUser, availableGroups[index]));
                                newUser.Save();
                            }
                        }

                        // REDIRECT TO EDIT FORM IF INDICATED
                        if (((Button)sender).ID == "AddEditButton")
                        {
                            Response.Redirect("EditUser.aspx?UserId=" + newUser.Id.ToString());
                        }

                        // NO REDIRECT, DISPLAY A CONFIRMATION FOR CREATED USER
                        UserAddedMessage.Text    = string.Format(UserAddedMessage.Text, newUser.UserName);
                        UserAddedMessage.Visible = true;

                        // RESET THE ADD FORM FIELDS
                        AddEmail.Text           = String.Empty;
                        AddPassword.Text        = String.Empty;
                        AddConfirmPassword.Text = String.Empty;
                        AddGroup.SelectedIndex  = -1;

                        //REBIND THE SEARCH
                        UserGrid.DataBind();
                    }
                    else
                    {
                        // CREATE USER FAILED WITHIN THE API
                        switch (status)
                        {
                        case MembershipCreateStatus.DuplicateEmail:
                        case MembershipCreateStatus.DuplicateUserName:
                            AddCustomValidationError(phEmailValidation, AddEmail, "The email address is already registered.");
                            break;

                        case MembershipCreateStatus.InvalidEmail:
                        case MembershipCreateStatus.InvalidUserName:
                            AddCustomValidationError(phEmailValidation, AddEmail, "The email address is invalid.");
                            break;

                        case MembershipCreateStatus.InvalidPassword:
                            AddCustomValidationError(phPasswordValidation, AddPassword, "The password is invalid.");
                            break;

                        default:
                            AddCustomValidationError(phEmailValidation, AddEmail, "Unexpected error: " + status.ToString());
                            break;
                        }
                        AddPopup.Show();
                    }
                }
                else
                {
                    AddPopup.Show();
                }
            }
            else
            {
                AddPopup.Show();
            }
        }
Esempio n. 11
0
        private bool CustomValidation()
        {
            bool hasErrors = false;

            if (trAmount.Visible)
            {
                decimal amount = AlwaysConvert.ToDecimal(Request.Form[Amount.UniqueID]);
                if (amount <= 0 || (this.MaxPaymentAmount > 0 && amount > this.MaxPaymentAmount))
                {
                    CustomValidator invalidAmount = new CustomValidator();
                    invalidAmount.ID = "invalidAmountValidator";
                    invalidAmount.ValidationGroup = this.ValidationGroup;
                    invalidAmount.Text            = "*";
                    invalidAmount.ErrorMessage    = "Invalid amount.  Payment must be greater than zero and no more than " + MaxPaymentAmount.LSCurrencyFormat("lc") + ".";
                    invalidAmount.IsValid         = false;
                    phAmount.Controls.Add(invalidAmount);
                    hasErrors = true;
                }
            }

            //if intl instructions are visible, we must validate additional rules
            if (trIntlInstructions.Visible)
            {
                PaymentMethod m = PaymentMethodDataSource.Load(AlwaysConvert.ToInt(CardType.SelectedValue));
                if (m != null)
                {
                    if (m.IsIntlDebitCard())
                    {
                        // INTERNATIONAL DEBIT CARD, ISSUE NUMBER OR START DATE REQUIRED
                        bool invalidIssueNumber = (!Regex.IsMatch(IssueNumber.Text, "\\d{1,2}"));
                        bool invalidStartDate   = ((StartDateMonth.SelectedIndex == 0) || (StartDateYear.SelectedIndex == 0));
                        if (invalidIssueNumber && invalidStartDate)
                        {
                            IntlDebitValidator1.IsValid = false;
                            IntlDebitValidator2.IsValid = false;
                            hasErrors = true;
                        }
                        // CHECK START DATE IS IN PAST
                        int selYear = AlwaysConvert.ToInt(StartDateYear.SelectedValue);
                        int curYear = DateTime.Now.Year;
                        if (selYear > curYear)
                        {
                            StartDateValidator1.IsValid = false;
                            hasErrors = true;
                        }
                        else if (selYear == curYear)
                        {
                            int selMonth = AlwaysConvert.ToInt(StartDateMonth.SelectedValue);
                            int curMonth = DateTime.Now.Month;
                            if (selMonth > curMonth)
                            {
                                StartDateValidator1.IsValid = false;
                                hasErrors = true;
                            }
                        }
                    }
                    else
                    {
                        // CREDIT CARD, CVV IS REQUIRED
                        if (!Regex.IsMatch(SecurityCode.Text, "\\d{3,4}"))
                        {
                            SecurityCodeValidator2.IsValid = false;
                            hasErrors = true;
                        }
                    }
                }
            }

            return(!hasErrors);
        }
        protected void SaveButton_Click(object sender, System.EventArgs e)
        {
            if (Page.IsValid)
            {
                //UPDATE NAME
                _ShipMethod.Name = Name.Text;
                //UPDATE RATE
                _ShipMethod.ServiceCode = ServiceCode.SelectedValue;
                //UPDATE SURCHARGE
                _ShipMethod.Surcharge = AlwaysConvert.ToDecimal(Surcharge.Text);
                if (_ShipMethod.Surcharge < 0)
                {
                    _ShipMethod.Surcharge = 0;
                }
                if (_ShipMethod.Surcharge > 0)
                {
                    _ShipMethod.SurchargeMode      = (SurchargeMode)AlwaysConvert.ToByte(SurchargeMode.SelectedValue);
                    _ShipMethod.SurchargeIsVisible = (SurchargeIsVisible.SelectedIndex > 0);
                }
                else
                {
                    _ShipMethod.SurchargeMode      = 0;
                    _ShipMethod.SurchargeIsVisible = false;
                }
                if (_ShipMethod.SurchargeIsVisible)
                {
                    _ShipMethod.SurchargeTaxCodeId = AlwaysConvert.ToInt(SurchargeTaxCode.SelectedValue);
                }
                else
                {
                    _ShipMethod.SurchargeTaxCodeId = 0;
                }

                //UPDATE WAREHOUSES
                _ShipMethod.Warehouses.Clear();
                _ShipMethod.Save();
                if (UseWarehouseRestriction.SelectedIndex > 0)
                {
                    foreach (ListItem item in WarehouseList.Items)
                    {
                        Warehouse warehouse = WarehouseDataSource.Load(AlwaysConvert.ToInt(item.Value));
                        if (item.Selected)
                        {
                            _ShipMethod.Warehouses.Add(warehouse);
                        }
                    }
                }
                //UPDATE ZONES
                _ShipMethod.ShipZones.Clear();
                _ShipMethod.Save();
                if (UseZoneRestriction.SelectedIndex > 0)
                {
                    foreach (ListItem item in ZoneList.Items)
                    {
                        ShipZone shipZone = ShipZoneDataSource.Load(AlwaysConvert.ToInt(item.Value));
                        if (item.Selected)
                        {
                            _ShipMethod.ShipZones.Add(shipZone);
                        }
                    }
                }
                //UPDATE ROLES
                _ShipMethod.Groups.Clear();
                if (UseGroupRestriction.SelectedIndex > 0)
                {
                    foreach (ListItem item in GroupList.Items)
                    {
                        CommerceBuilder.Users.Group group = GroupDataSource.Load(AlwaysConvert.ToInt(item.Value));
                        if (item.Selected)
                        {
                            _ShipMethod.Groups.Add(group);
                        }
                    }
                }
                //UPDATE MIN PURCHASE
                _ShipMethod.MinPurchase = AlwaysConvert.ToDecimal(MinPurchase.Text);
                //UPDATE MIN PURCHASE
                _ShipMethod.MaxPurchase = AlwaysConvert.ToDecimal(MaxPurchase.Text);
                //UPDATE TAX CODES
                _ShipMethod.TaxCode = TaxCodeDataSource.Load(AlwaysConvert.ToInt(TaxCode.SelectedValue));
                //SAVE METHOD AND REDIRECT TO LIST
                _ShipMethod.Save();
                RedirectMe();
            }
        }
Esempio n. 13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string eventTarget = Request["__EVENTTARGET"];

            if (string.IsNullOrEmpty(eventTarget) || !eventTarget.EndsWith("PageSizeOptions"))
            {
                string pageSizeOption = Request.QueryString["ps"];
                if (!string.IsNullOrEmpty(pageSizeOption))
                {
                    PageSizeOptions.ClearSelection();
                    ListItem item = PageSizeOptions.Items.FindByValue(pageSizeOption);
                    if (item != null)
                    {
                        item.Selected = true;
                    }
                }
            }
            else
            if (eventTarget.EndsWith("PageSizeOptions"))
            {
                string url = Request.RawUrl;
                if (url.Contains("?"))
                {
                    url = Request.RawUrl.Substring(0, Request.RawUrl.IndexOf("?"));
                }
                url += "?s=" + SortResults.SelectedValue;
                url += "&ps=" + PageSizeOptions.SelectedValue;
                Response.Redirect(url);
            }

            _pageSize = AlwaysConvert.ToInt(PageSizeOptions.SelectedValue);
            SetPagerIndex();

            CatalogNodeList.RepeatColumns = Cols;
            if (IsValidCategory())
            {
                //INITIALIZE THE CONTENT NODES
                _ContentNodes = new List <Product>();
                List <Product> visibleNodes = (List <Product>)ProductDataSource.LoadForCategory(true, this.CategoryId, false, true, SortResults.SelectedValue, _pageSize, (_HiddenPageIndex * _pageSize));

                // CUSTOM SORTING ON VOLUME PRICES
                if (SortResults.SelectedValue.Equals("Price ASC"))
                {
                    visibleNodes = visibleNodes.OrderBy(x => (x.VolumeDiscounts.Any() && x.VolumeDiscounts[0].Levels.Any()) ? x.VolumeDiscounts[0].Levels.First().DiscountAmount : x.Price).ThenBy(x => (x.VolumeDiscounts.Any() && x.VolumeDiscounts[0].Levels.Any()) ? x.VolumeDiscounts[0].Levels.Last().DiscountAmount : 0).ToList(); //Lowest-Highest
                }
                else if (SortResults.SelectedValue.Equals("Price DESC"))
                {
                    visibleNodes = visibleNodes.OrderByDescending(x => (x.VolumeDiscounts.Any() && x.VolumeDiscounts[0].Levels.Any()) ? x.VolumeDiscounts[0].Levels.First().DiscountAmount : x.Price).ThenByDescending(x => (x.VolumeDiscounts.Any() && x.VolumeDiscounts[0].Levels.Any()) ? x.VolumeDiscounts[0].Levels.Last().DiscountAmount : 0).ToList();  //Highest-Lowest
                }

                if (visibleNodes.Count > 0)
                {
                    _ContentNodes.AddRange(visibleNodes);

                    // DELAYED QUERIES TO EAGER LOAD RELATED DATA FOR PERFORMANCE BOOST
                    List <int> ids         = visibleNodes.Select(p => p.Id).ToList();
                    var        futureQuery = NHibernateHelper.QueryOver <Product>()
                                             .AndRestrictionOn(p => p.Id).IsIn(ids)
                                             .Fetch(p => p.Specials).Eager
                                             .Future <Product>();

                    NHibernateHelper.QueryOver <Product>()
                    .AndRestrictionOn(p => p.Id).IsIn(ids)
                    .Fetch(p => p.ProductOptions).Eager
                    .Future <Product>();

                    NHibernateHelper.QueryOver <Product>()
                    .AndRestrictionOn(p => p.Id).IsIn(ids)
                    .Fetch(p => p.ProductKitComponents).Eager
                    .Future <Product>();

                    NHibernateHelper.QueryOver <Product>()
                    .AndRestrictionOn(p => p.Id).IsIn(ids)
                    .Fetch(p => p.ProductTemplates).Eager
                    .Future <Product>();

                    NHibernateHelper.QueryOver <Product>()
                    .AndRestrictionOn(p => p.Id).IsIn(ids)
                    .Fetch(p => p.Reviews).Eager
                    .Future <Product>();

                    futureQuery.ToList();
                }

                if (_pageSize == 0)
                {
                    _pageSize = _ContentNodes.Count;
                }

                int minimumPageSize = AlwaysConvert.ToInt(PageSizeOptions.Items[0].Value);
                PageSizePanel.Visible = _searchResultCount > minimumPageSize;

                //BIND PAGE
                BindPage();
            }

            int manufecturerCount = ManufacturerDataSource.CountAll();

            foreach (ListItem li in SortResults.Items)
            {
                if (li.Value.StartsWith("Manufacturer"))
                {
                    li.Enabled = manufecturerCount > 0;
                }
            }
        }
 protected void UploadButton_Click(object sender, EventArgs e)
 {
     if (UploadedFile.HasFile)
     {
         bool success = true;
         StoreSettingsManager settings = AbleContext.Current.Store.Settings;
         if (!BaseFileName.Text.Contains("."))
         {
             BaseFileName.Text += System.IO.Path.GetExtension(UploadedFile.FileName);
         }
         string safeFileName = string.Empty;
         safeFileName = FileHelper.GetSafeBaseImageName(BaseFileName.Text, true);
         if (!string.IsNullOrEmpty(safeFileName) && FileHelper.IsExtensionValid(safeFileName, AbleContext.Current.Store.Settings.FileExt_Assets))
         {
             //save the image to do the resizing work
             if (!Resize.Checked)
             {
                 //JUST SAVE THE IMAGE AND ASSOCIATE WITH PRODUCT
                 string tempImagePath = FileHelper.BaseImagePath + safeFileName;
                 UploadedFile.SaveAs(tempImagePath);
                 ProductImage newImage = new ProductImage();
                 newImage.ProductId = _ProductId;
                 newImage.ImageUrl  = FileHelper.BaseImageUrlPath + safeFileName;
                 newImage.Moniker   = Moniker.Text.Trim();
                 newImage.Save();
             }
             else
             {
                 string tempImagePath = FileHelper.BaseImagePath + Guid.NewGuid().ToString("N") + ".jpg";
                 UploadedFile.SaveAs(tempImagePath);
                 if (FileHelper.IsImageFile(tempImagePath))
                 {
                     using (System.Drawing.Image originalImage = System.Drawing.Image.FromFile(tempImagePath))
                     {
                         FileHelper.WriteImageFile(originalImage, FileHelper.BaseImagePath + safeFileName, AlwaysConvert.ToInt(CustomWidth.Text), AlwaysConvert.ToInt(CustomHeight.Text), MaintainAspectRatio.Checked, AlwaysConvert.ToInt(Quality.Text));
                         ProductImage newImage = new ProductImage();
                         newImage.ProductId = _ProductId;
                         newImage.ImageUrl  = FileHelper.BaseImageUrlPath + safeFileName;
                         newImage.Moniker   = Moniker.Text.Trim();
                         newImage.Save();
                     }
                 }
                 else
                 {
                     success = false;
                     CustomValidator invalidFile = new CustomValidator();
                     invalidFile.Text         = "*";
                     invalidFile.ErrorMessage = "You did not upload a valid file.";
                     invalidFile.IsValid      = false;
                     phInvalidFile.Controls.Add(invalidFile);
                 }
                 try
                 {
                     if (System.IO.File.Exists(tempImagePath))
                     {
                         System.IO.File.Delete(tempImagePath);
                     }
                 }
                 catch (Exception ex)
                 {
                     Logger.Warn("Could not delete temporary image file " + tempImagePath, ex);
                 }
             }
             if (success)
             {
                 Response.Redirect("AdditionalImages.aspx?ProductId=" + _ProductId.ToString());
             }
         }
         else
         {
             CustomValidator filetype = new CustomValidator();
             filetype.IsValid           = false;
             filetype.ControlToValidate = "BaseFileName";
             filetype.ErrorMessage      = "'" + safeFileName + "' is not a valid file name.";
             filetype.Text = "*";
             phValidFiles.Controls.Add(filetype);
         }
     }
 }
        /// <summary>
        /// Saves this ShipGateway object to the database.
        /// </summary>
        /// <returns><b>SaveResult</b> enumeration that represents the result of the save operation.</returns>
        public virtual SaveResult Save()
        {
            if (this.IsDirty)
            {
                Database database     = Token.Instance.Database;
                bool     recordExists = true;

                //SET EMPTY STOREID TO CURRENT CONTEXT
                if (this.StoreId == 0)
                {
                    this.StoreId = Token.Instance.StoreId;
                }
                if (this.ShipGatewayId == 0)
                {
                    recordExists = false;
                }

                if (recordExists)
                {
                    //verify whether record is already present
                    StringBuilder selectQuery = new StringBuilder();
                    selectQuery.Append("SELECT COUNT(*) As RecordCount FROM ac_ShipGateways");
                    selectQuery.Append(" WHERE ShipGatewayId = @ShipGatewayId");
                    using (DbCommand selectCommand = database.GetSqlStringCommand(selectQuery.ToString()))
                    {
                        database.AddInParameter(selectCommand, "@ShipGatewayId", System.Data.DbType.Int32, this.ShipGatewayId);
                        if ((int)database.ExecuteScalar(selectCommand) == 0)
                        {
                            recordExists = false;
                        }
                    }
                }

                int result = 0;
                if (recordExists)
                {
                    //UPDATE
                    StringBuilder updateQuery = new StringBuilder();
                    updateQuery.Append("UPDATE ac_ShipGateways SET ");
                    updateQuery.Append("StoreId = @StoreId");
                    updateQuery.Append(", Name = @Name");
                    updateQuery.Append(", ClassId = @ClassId");
                    updateQuery.Append(", ConfigData = @ConfigData");
                    updateQuery.Append(", ReCrypt = @ReCrypt");
                    updateQuery.Append(", Enabled = @Enabled");
                    updateQuery.Append(" WHERE ShipGatewayId = @ShipGatewayId");
                    using (DbCommand updateCommand = database.GetSqlStringCommand(updateQuery.ToString()))
                    {
                        database.AddInParameter(updateCommand, "@ShipGatewayId", System.Data.DbType.Int32, this.ShipGatewayId);
                        database.AddInParameter(updateCommand, "@StoreId", System.Data.DbType.Int32, this.StoreId);
                        database.AddInParameter(updateCommand, "@Name", System.Data.DbType.String, this.Name);
                        database.AddInParameter(updateCommand, "@ClassId", System.Data.DbType.String, this.ClassId);
                        database.AddInParameter(updateCommand, "@ConfigData", System.Data.DbType.String, NullableData.DbNullify(this.ConfigData));
                        database.AddInParameter(updateCommand, "@ReCrypt", System.Data.DbType.Boolean, this.ReCrypt);
                        database.AddInParameter(updateCommand, "@Enabled", System.Data.DbType.Boolean, this.Enabled);
                        //RESULT IS NUMBER OF RECORDS AFFECTED
                        result = database.ExecuteNonQuery(updateCommand);
                    }
                }
                else
                {
                    //INSERT
                    StringBuilder insertQuery = new StringBuilder();
                    insertQuery.Append("INSERT INTO ac_ShipGateways (StoreId, Name, ClassId, ConfigData, ReCrypt, Enabled)");
                    insertQuery.Append(" VALUES (@StoreId, @Name, @ClassId, @ConfigData, @ReCrypt, @Enabled)");
                    insertQuery.Append("; SELECT Scope_Identity()");
                    using (DbCommand insertCommand = database.GetSqlStringCommand(insertQuery.ToString()))
                    {
                        database.AddInParameter(insertCommand, "@ShipGatewayId", System.Data.DbType.Int32, this.ShipGatewayId);
                        database.AddInParameter(insertCommand, "@StoreId", System.Data.DbType.Int32, this.StoreId);
                        database.AddInParameter(insertCommand, "@Name", System.Data.DbType.String, this.Name);
                        database.AddInParameter(insertCommand, "@ClassId", System.Data.DbType.String, this.ClassId);
                        database.AddInParameter(insertCommand, "@ConfigData", System.Data.DbType.String, NullableData.DbNullify(this.ConfigData));
                        database.AddInParameter(insertCommand, "@ReCrypt", System.Data.DbType.Boolean, this.ReCrypt);
                        database.AddInParameter(insertCommand, "@Enabled", System.Data.DbType.Boolean, this.Enabled);
                        //RESULT IS NEW IDENTITY;
                        result = AlwaysConvert.ToInt(database.ExecuteScalar(insertCommand));
                        this._ShipGatewayId = result;
                    }
                }
                this.SaveChildren();

                //OBJECT IS DIRTY IF NO RECORDS WERE UPDATED OR INSERTED
                this.IsDirty = (result == 0);
                if (this.IsDirty)
                {
                    return(SaveResult.Failed);
                }
                else
                {
                    return(recordExists ? SaveResult.RecordUpdated : SaveResult.RecordInserted);
                }
            }

            //SAVE IS SUCCESSFUL IF OBJECT IS NOT DIRTY
            return(SaveResult.NotDirty);
        }
        protected void AddProductPrice_PreRender(object sender, EventArgs e)
        {
            int     productId = AlwaysConvert.ToInt(AddProductId.Value);
            Product product   = ProductDataSource.Load(productId);

            if (product != null)
            {
                //GET THE SELECTED KIT OPTIONS
                GetSelectedKitOptions(product);
                //SET THE CURRENT CALCULATED PRICE
                string            optionList            = ProductVariantDataSource.GetOptionList(productId, _SelectedOptions, true);
                bool              calculateOneTimePrice = AlwaysConvert.ToBool(OptionalSubscription.SelectedValue, false);
                ProductCalculator pcalc = ProductCalculator.LoadForProduct(productId, 1, optionList, AlwaysConvert.ToList(",", _SelectedKitProducts), _UserId, false, calculateOneTimePrice);
                AddProductPrice.Text = string.Format("{0:F2}", pcalc.Price);

                if (product.IsSubscription)
                {
                    if (product.SubscriptionPlan.IsRecurring)
                    {
                        if (!calculateOneTimePrice)
                        {
                            short frequency = product.SubscriptionPlan.PaymentFrequencyType == PaymentFrequencyType.Optional ? AlwaysConvert.ToInt16(AutoDeliveryInterval.SelectedValue) : product.SubscriptionPlan.PaymentFrequency;
                            SubscriptionMessage.Text    = ProductHelper.GetRecurringPaymentMessage(product.Price, 0, product.SubscriptionPlan, frequency);
                            SubscriptionMessage.Visible = true;
                        }
                        else
                        {
                            SubscriptionMessage.Visible = false;
                        }
                    }
                    else
                    {
                        trSubscriptionRow.Visible = product.SubscriptionPlan.IsOptional;
                    }
                }
                else
                {
                    trSubscriptionRow.Visible = false;
                }

                if (product.UseVariablePrice && !product.IsSubscription && !product.IsKit)
                {
                    AddProductVariablePrice.Text    = string.Format("{0:F2}", pcalc.Price);
                    AddProductVariablePrice.Visible = true;
                    string varPriceText = string.Empty;
                    if (product.MinimumPrice > 0)
                    {
                        if (product.MaximumPrice > 0)
                        {
                            varPriceText = string.Format("(between {0} and {1})", product.MinimumPrice.LSCurrencyFormat("lcf"), product.MaximumPrice.LSCurrencyFormat("lcf"));
                        }
                        else
                        {
                            varPriceText = string.Format("(at least {0})", product.MinimumPrice.LSCurrencyFormat("lcf"));
                        }
                    }
                    else if (product.MaximumPrice > 0)
                    {
                        varPriceText = string.Format("({0} maximum)", product.MaximumPrice.LSCurrencyFormat("lcf"));
                    }
                    phVariablePrice.Controls.Add(new LiteralControl(varPriceText));
                }
                AddProductPrice.Visible = !AddProductVariablePrice.Visible;
                if ((AddProductPrice.Visible && _Basket.UserId == AbleContext.Current.UserId) || (product.IsKit))
                {
                    AddProductPrice.Enabled = false;
                }
            }
        }
Esempio n. 17
0
 protected void DateFilter_SelectedIndexChanged(object sender, EventArgs e)
 {
     ViewState["ReportDate"] = new DateTime(AlwaysConvert.ToInt(YearList.SelectedValue), AlwaysConvert.ToInt(MonthList.SelectedValue), 1);
     GenerateReport();
 }
        protected void InventoryAlertUpdate()
        {
            int     productId = AlwaysConvert.ToInt(AddProductId.Value);
            Product product   = ProductDataSource.Load(productId);

            if (product != null)
            {
                // WE HAVE A VALID PRODUCT, ARE ANY AVAILABLE OPTIONS SELECTED?
                bool allProductOptionsSelected = (_SelectedOptions.Count == product.ProductOptions.Count);
                if (allProductOptionsSelected)
                {
                    // OPTIONS ARE GOOD, VERIFY ANY REQUIRED KIT OPTIONS ARE SELECTED
                    GetSelectedKitOptions(product);
                    bool requiredKitOptionsSelected = AbleCommerce.Code.ProductHelper.RequiredKitOptionsSelected(product, _SelectedKitProducts);
                    if (requiredKitOptionsSelected)
                    {
                        // KIT OPTIONS ARE ALSO VALID, DETERMINE APPROPRIATE WARNINGS
                        Store         store           = AbleContext.Current.Store;
                        List <string> warningMessages = new List <string>();

                        string optionList = string.Empty;
                        if (product.ProductOptions.Count > 0)
                        {
                            // OPTIONS ARE PRESENT, CHECK AVAILABLILITY
                            optionList = ProductVariantDataSource.GetOptionList(productId, _SelectedOptions, true);
                            ProductVariant variant = ProductVariantDataSource.LoadForOptionList(product.Id, optionList);
                            if (!variant.Available)
                            {
                                warningMessages.Add("The selected variant is marked as unavailable.");
                            }

                            // WE ALSO NEED TO ALERT INVENTORY IF ENABLED AT VARIANT LEVEL AND THIS IS NOT A KIT
                            if (_StoreInventoryEnabled &&
                                product.KitStatus != KitStatus.Master &&
                                product.InventoryMode == InventoryMode.Variant)
                            {
                                warningMessages.Add("The selected variant has a current stock level of " + variant.InStock + ".");
                            }
                        }

                        // CHECK STOCK QUANTITY FOR PRODUCT, IF STORE INVENTORY IS ENABLED
                        // AND THE STOCK IS MANAGED AT THE PRODUCT LEVEL OR THIS IS A KIT
                        if (_StoreInventoryEnabled && (product.InventoryMode == InventoryMode.Product || product.KitStatus == KitStatus.Master))
                        {
                            InventoryManagerData inv = _InventoryManager.CheckStock(productId, optionList, _SelectedKitProducts);
                            if (!inv.AllowBackorder)
                            {
                                if (product.KitStatus == KitStatus.Master)
                                {
                                    // INVENTORY MESSAGE FOR KIT PRODUCTS
                                    warningMessages.Add("The selected configuration has a current stock level of " + inv.InStock + ".");
                                }
                                else
                                {
                                    // NOT KIT OR VARIANT
                                    warningMessages.Add("This product has a current stock level of " + inv.InStock + ".");
                                }
                            }
                        }

                        // SHOW ANY WARNING MESSAGES
                        if (warningMessages.Count > 0)
                        {
                            InventoryWarningMessage.Text = "Note: " + string.Join(" ", warningMessages.ToArray());
                            trInventoryWarning.Visible   = true;
                        }
                    }
                }
            }
        }
Esempio n. 19
0
        private void SaveShipMethod()
        {
            //UPDATE NAME
            _ShipMethod.Name = Name.Text;
            //UPDATE RATE
            ShipRateMatrix shipRateMatrixItem;

            if (_ShipMethod.ShipRateMatrices.Count != 1)
            {
                _ShipMethod.ShipRateMatrices.DeleteAll();
                shipRateMatrixItem            = new ShipRateMatrix();
                shipRateMatrixItem.ShipMethod = _ShipMethod;
                _ShipMethod.ShipRateMatrices.Add(shipRateMatrixItem);
            }
            else
            {
                shipRateMatrixItem = _ShipMethod.ShipRateMatrices[0];
            }
            shipRateMatrixItem.RangeStart = 0;
            shipRateMatrixItem.RangeEnd   = 0;
            shipRateMatrixItem.Rate       = AlwaysConvert.ToDecimal(Rate.Text);
            shipRateMatrixItem.IsPercent  = false;
            //UPDATE SURCHARGE
            _ShipMethod.Surcharge = AlwaysConvert.ToDecimal(Surcharge.Text);
            if (_ShipMethod.Surcharge < 0)
            {
                _ShipMethod.Surcharge = 0;
            }
            if (_ShipMethod.Surcharge > 0)
            {
                _ShipMethod.SurchargeMode      = (SurchargeMode)AlwaysConvert.ToByte(SurchargeMode.SelectedValue);
                _ShipMethod.SurchargeIsVisible = (SurchargeIsVisible.SelectedIndex > 0);
            }
            else
            {
                _ShipMethod.SurchargeMode      = 0;
                _ShipMethod.SurchargeIsVisible = false;
            }
            if (_ShipMethod.SurchargeIsVisible)
            {
                _ShipMethod.SurchargeTaxCodeId = AlwaysConvert.ToInt(SurchargeTaxCode.SelectedValue);
            }
            else
            {
                _ShipMethod.SurchargeTaxCodeId = 0;
            }
            //UPDATE WAREHOUSES
            _ShipMethod.Warehouses.Clear();
            _ShipMethod.Save();
            if (UseWarehouseRestriction.SelectedIndex > 0)
            {
                foreach (ListItem item in WarehouseList.Items)
                {
                    Warehouse warehouse = WarehouseDataSource.Load(AlwaysConvert.ToInt(item.Value));
                    if (item.Selected)
                    {
                        _ShipMethod.Warehouses.Add(warehouse);
                    }
                }
            }
            //UPDATE ZONES
            _ShipMethod.ShipZones.Clear();
            _ShipMethod.Save();
            if (UseZoneRestriction.SelectedIndex > 0)
            {
                foreach (ListItem item in ZoneList.Items)
                {
                    ShipZone shipZone = ShipZoneDataSource.Load(AlwaysConvert.ToInt(item.Value));
                    if (item.Selected)
                    {
                        _ShipMethod.ShipZones.Add(shipZone);
                    }
                }
            }
            //UPDATE ROLES
            _ShipMethod.Groups.Clear();
            _ShipMethod.Save();
            if (UseGroupRestriction.SelectedIndex > 0)
            {
                foreach (ListItem item in GroupList.Items)
                {
                    CommerceBuilder.Users.Group group = GroupDataSource.Load(AlwaysConvert.ToInt(item.Value));
                    if (item.Selected)
                    {
                        _ShipMethod.Groups.Add(group);
                    }
                }
            }
            //UPDATE MIN PURCHASE
            _ShipMethod.MinPurchase = AlwaysConvert.ToDecimal(MinPurchase.Text);
            //UPDATE MAX PURCHASE
            _ShipMethod.MaxPurchase = AlwaysConvert.ToDecimal(MaxPurchase.Text);
            //UPDATE TAX CODES
            _ShipMethod.TaxCode = TaxCodeDataSource.Load(AlwaysConvert.ToInt(TaxCode.SelectedValue));
            //SAVE METHOD AND REDIRECT TO LIST
            _ShipMethod.Save();
        }
Esempio n. 20
0
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            int _NewCategoryId = AlwaysConvert.ToInt(NewPath.SelectedValue);

            if (_CategoryId != _NewCategoryId)
            {
                Category currentCategory = CategoryDataSource.Load(_CategoryId);
                Category targetCategory  = CategoryDataSource.Load(_NewCategoryId);
                // CATEGORIES CAN ONLY BE MOVED, NOT MULTIPARENTED
                if (_Categories != null)
                {
                    foreach (Category category in _Categories)
                    {
                        category.ParentId = _NewCategoryId;
                        category.Save();
                    }
                }
                bool moveAll    = (MoveOptions.SelectedValue == "MoveAll");
                bool moveSingle = (MoveOptions.SelectedValue == "MoveSingle");
                // LOOP SELECTED ITEMS AND MOVE AS NEEDED
                IDatabaseSessionManager database = AbleContext.Current.Database;
                database.BeginTransaction();
                foreach (ICatalogable catalogItem in _CatalogItems)
                {
                    if (catalogItem is Product)
                    {
                        Product product = (Product)catalogItem;
                        if (moveAll)
                        {
                            product.Categories.Clear();
                        }
                        else if (moveSingle)
                        {
                            product.Categories.Remove(_CategoryId);
                        }
                        if (!product.Categories.Contains(_NewCategoryId))
                        {
                            product.Categories.Add(_NewCategoryId);
                        }
                        product.Categories.Save();
                    }
                    else if (catalogItem is Webpage)
                    {
                        Webpage webpage = (Webpage)catalogItem;
                        if (moveAll)
                        {
                            webpage.Categories.Clear();
                        }
                        else if (moveSingle)
                        {
                            webpage.Categories.Remove(_CategoryId);
                        }
                        if (!webpage.Categories.Contains(_NewCategoryId))
                        {
                            webpage.Categories.Add(_NewCategoryId);
                        }
                        webpage.Categories.Save();
                    }
                    else if (catalogItem is Link)
                    {
                        Link link = (Link)catalogItem;
                        if (moveAll)
                        {
                            link.Categories.Clear();
                        }
                        else if (moveSingle)
                        {
                            link.Categories.Remove(_CategoryId);
                        }
                        if (!link.Categories.Contains(_NewCategoryId))
                        {
                            link.Categories.Add(_NewCategoryId);
                        }
                        link.Categories.Save();
                    }
                }
                database.CommitTransaction();
            }
            Response.Redirect("Browse.aspx?CategoryId=" + _NewCategoryId.ToString());
        }
Esempio n. 21
0
        /// <summary>
        /// Saves this EmailTemplate object to the database.
        /// </summary>
        /// <returns><b>SaveResult</b> enumeration that represents the result of the save operation.</returns>
        protected SaveResult BaseSave()
        {
            if (this.IsDirty)
            {
                Database database     = Token.Instance.Database;
                bool     recordExists = true;

                //SET EMPTY STOREID TO CURRENT CONTEXT
                if (this.StoreId == 0)
                {
                    this.StoreId = Token.Instance.StoreId;
                }
                if (this.EmailTemplateId == 0)
                {
                    recordExists = false;
                }

                if (recordExists)
                {
                    //verify whether record is already present
                    StringBuilder selectQuery = new StringBuilder();
                    selectQuery.Append("SELECT COUNT(*) As RecordCount FROM ac_EmailTemplates");
                    selectQuery.Append(" WHERE EmailTemplateId = @EmailTemplateId");
                    using (DbCommand selectCommand = database.GetSqlStringCommand(selectQuery.ToString()))
                    {
                        database.AddInParameter(selectCommand, "@EmailTemplateId", System.Data.DbType.Int32, this.EmailTemplateId);
                        if ((int)database.ExecuteScalar(selectCommand) == 0)
                        {
                            recordExists = false;
                        }
                    }
                }

                int result = 0;
                if (recordExists)
                {
                    //UPDATE
                    StringBuilder updateQuery = new StringBuilder();
                    updateQuery.Append("UPDATE ac_EmailTemplates SET ");
                    updateQuery.Append("StoreId = @StoreId");
                    updateQuery.Append(", Name = @Name");
                    updateQuery.Append(", ToAddress = @ToAddress");
                    updateQuery.Append(", FromAddress = @FromAddress");
                    updateQuery.Append(", ReplyToAddress = @ReplyToAddress");
                    updateQuery.Append(", CCList = @CCList");
                    updateQuery.Append(", BCCList = @BCCList");
                    updateQuery.Append(", Subject = @Subject");
                    updateQuery.Append(", ContentFileName = @ContentFileName");
                    updateQuery.Append(", IsHTML = @IsHTML");
                    updateQuery.Append(" WHERE EmailTemplateId = @EmailTemplateId");
                    using (DbCommand updateCommand = database.GetSqlStringCommand(updateQuery.ToString()))
                    {
                        database.AddInParameter(updateCommand, "@EmailTemplateId", System.Data.DbType.Int32, this.EmailTemplateId);
                        database.AddInParameter(updateCommand, "@StoreId", System.Data.DbType.Int32, this.StoreId);
                        database.AddInParameter(updateCommand, "@Name", System.Data.DbType.String, this.Name);
                        database.AddInParameter(updateCommand, "@ToAddress", System.Data.DbType.String, this.ToAddress);
                        database.AddInParameter(updateCommand, "@FromAddress", System.Data.DbType.String, this.FromAddress);
                        database.AddInParameter(updateCommand, "@ReplyToAddress", System.Data.DbType.String, NullableData.DbNullify(this.ReplyToAddress));
                        database.AddInParameter(updateCommand, "@CCList", System.Data.DbType.String, NullableData.DbNullify(this.CCList));
                        database.AddInParameter(updateCommand, "@BCCList", System.Data.DbType.String, NullableData.DbNullify(this.BCCList));
                        database.AddInParameter(updateCommand, "@Subject", System.Data.DbType.String, NullableData.DbNullify(this.Subject));
                        database.AddInParameter(updateCommand, "@ContentFileName", System.Data.DbType.String, NullableData.DbNullify(this.ContentFileName));
                        database.AddInParameter(updateCommand, "@IsHTML", System.Data.DbType.Boolean, this.IsHTML);
                        //RESULT IS NUMBER OF RECORDS AFFECTED
                        result = database.ExecuteNonQuery(updateCommand);
                    }
                }
                else
                {
                    //INSERT
                    StringBuilder insertQuery = new StringBuilder();
                    insertQuery.Append("INSERT INTO ac_EmailTemplates (StoreId, Name, ToAddress, FromAddress, ReplyToAddress, CCList, BCCList, Subject, ContentFileName, IsHTML)");
                    insertQuery.Append(" VALUES (@StoreId, @Name, @ToAddress, @FromAddress, @ReplyToAddress, @CCList, @BCCList, @Subject, @ContentFileName, @IsHTML)");
                    insertQuery.Append("; SELECT Scope_Identity()");
                    using (DbCommand insertCommand = database.GetSqlStringCommand(insertQuery.ToString()))
                    {
                        database.AddInParameter(insertCommand, "@EmailTemplateId", System.Data.DbType.Int32, this.EmailTemplateId);
                        database.AddInParameter(insertCommand, "@StoreId", System.Data.DbType.Int32, this.StoreId);
                        database.AddInParameter(insertCommand, "@Name", System.Data.DbType.String, this.Name);
                        database.AddInParameter(insertCommand, "@ToAddress", System.Data.DbType.String, this.ToAddress);
                        database.AddInParameter(insertCommand, "@FromAddress", System.Data.DbType.String, this.FromAddress);
                        database.AddInParameter(insertCommand, "@ReplyToAddress", System.Data.DbType.String, NullableData.DbNullify(this.ReplyToAddress));
                        database.AddInParameter(insertCommand, "@CCList", System.Data.DbType.String, NullableData.DbNullify(this.CCList));
                        database.AddInParameter(insertCommand, "@BCCList", System.Data.DbType.String, NullableData.DbNullify(this.BCCList));
                        database.AddInParameter(insertCommand, "@Subject", System.Data.DbType.String, NullableData.DbNullify(this.Subject));
                        database.AddInParameter(insertCommand, "@ContentFileName", System.Data.DbType.String, NullableData.DbNullify(this.ContentFileName));
                        database.AddInParameter(insertCommand, "@IsHTML", System.Data.DbType.Boolean, this.IsHTML);
                        //RESULT IS NEW IDENTITY;
                        result = AlwaysConvert.ToInt(database.ExecuteScalar(insertCommand));
                        this._EmailTemplateId = result;
                    }
                }
                this.SaveChildren();

                //OBJECT IS DIRTY IF NO RECORDS WERE UPDATED OR INSERTED
                this.IsDirty = (result == 0);
                if (this.IsDirty)
                {
                    return(SaveResult.Failed);
                }
                else
                {
                    return(recordExists ? SaveResult.RecordUpdated : SaveResult.RecordInserted);
                }
            }

            //SAVE IS SUCCESSFUL IF OBJECT IS NOT DIRTY
            return(SaveResult.NotDirty);
        }
Esempio n. 22
0
        protected void InitializeCatalogItems()
        {
            String items = Request.QueryString["Objects"];

            if (String.IsNullOrEmpty(items))
            {
                return;
            }
            String[]      itemsArray  = items.Split(',');
            List <String> categoryIds = new List <String>();
            List <String> productIds  = new List <String>();
            List <String> linkIds     = new List <String>();
            List <String> webpageIds  = new List <String>();

            // Sort out items in saperate lists
            foreach (String item in itemsArray)
            {
                String[]        itemValues      = item.Split(':');
                int             catalogNodeId   = AlwaysConvert.ToInt(itemValues[0]);
                CatalogNodeType catalogNodeType = (CatalogNodeType)AlwaysConvert.ToByte(itemValues[1]);
                switch (catalogNodeType)
                {
                case CatalogNodeType.Category:
                    categoryIds.Add(catalogNodeId.ToString());
                    break;

                case CatalogNodeType.Product:
                    productIds.Add(catalogNodeId.ToString());
                    break;

                case CatalogNodeType.Link:
                    linkIds.Add(catalogNodeId.ToString());
                    break;

                case CatalogNodeType.Webpage:
                    webpageIds.Add(catalogNodeId.ToString());
                    break;
                }
            }

            if (categoryIds.Count > 0)
            {
                ICriteria criteria = CommerceBuilder.DomainModel.NHibernateHelper.CreateCriteria <Category>();
                criteria.Add(Restrictions.In("Id", categoryIds.ToArray()));
                _Categories = CategoryDataSource.LoadForCriteria(criteria);
                if (_Categories != null && _Categories.Count > 0)
                {
                    foreach (Category category in _Categories)
                    {
                        _CatalogItems.Add(category);
                    }
                }
            }

            if (productIds.Count > 0)
            {
                ICriteria criteria = CommerceBuilder.DomainModel.NHibernateHelper.CreateCriteria <Product>();
                criteria.Add(Restrictions.In("Id", productIds.ToArray()));
                _Products = ProductDataSource.LoadForCriteria(criteria);
                if (_Products != null && _Products.Count > 0)
                {
                    foreach (Product product in _Products)
                    {
                        _CatalogItems.Add(product);
                    }
                }
            }

            if (linkIds.Count > 0)
            {
                ICriteria criteria = CommerceBuilder.DomainModel.NHibernateHelper.CreateCriteria <Link>();
                criteria.Add(Restrictions.In("Id", linkIds.ToArray()));
                _Links = LinkDataSource.LoadForCriteria(criteria);
                if (_Links != null && _Links.Count > 0)
                {
                    foreach (Link link in _Links)
                    {
                        _CatalogItems.Add(link);
                    }
                }
            }

            if (webpageIds.Count > 0)
            {
                ICriteria criteria = CommerceBuilder.DomainModel.NHibernateHelper.CreateCriteria <Webpage>();
                criteria.Add(Restrictions.In("Id", webpageIds.ToArray()));
                _Webpages = WebpageDataSource.LoadForCriteria(criteria);
                if (_Webpages != null && _Webpages.Count > 0)
                {
                    foreach (Webpage webpage in _Webpages)
                    {
                        _CatalogItems.Add(webpage);
                    }
                }
            }
        }
Esempio n. 23
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            _categoryId     = AlwaysConvert.ToInt(Request.QueryString["c"]);
            _manufacturerId = AlwaysConvert.ToInt(Request.QueryString["m"]);
            _keywords       = StringHelper.StripHtml(Server.UrlDecode(Request.QueryString["k"]));
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = StringHelper.StripHtml(_keywords).Trim();
            }

            _shopBy = StringHelper.StripHtml(Server.UrlDecode(Request.QueryString["shopby"]));
            if (!string.IsNullOrEmpty(_shopBy))
            {
                _shopBy = StringHelper.StripHtml(_shopBy).Trim();
            }

            string eventTarget = Request["__EVENTTARGET"];

            if (string.IsNullOrEmpty(eventTarget) || !eventTarget.EndsWith("PageSizeOptions"))
            {
                string pageSizeOption = Request.QueryString["ps"];
                if (!string.IsNullOrEmpty(pageSizeOption))
                {
                    PageSizeOptions.ClearSelection();
                    ListItem item = PageSizeOptions.Items.FindByValue(pageSizeOption);
                    if (item != null)
                    {
                        item.Selected = true;
                    }
                }
            }
            else
            if (eventTarget.EndsWith("PageSizeOptions"))
            {
                string url = Request.RawUrl;
                if (url.Contains("?"))
                {
                    url = Request.RawUrl.Substring(0, Request.RawUrl.IndexOf("?"));
                }
                url += "?s=" + SortResults.SelectedValue;
                url += "&ps=" + PageSizeOptions.SelectedValue;
                if (_categoryId != 0)
                {
                    url += "&c=" + _categoryId.ToString();
                }
                if (_manufacturerId != 0)
                {
                    url += "&m=" + _manufacturerId.ToString();
                }
                if (!string.IsNullOrEmpty(_keywords))
                {
                    url += "&k=" + _keywords;
                }
                if (!string.IsNullOrEmpty(_shopBy))
                {
                    url += "&shopby=" + _shopBy;
                }
                Response.Redirect(url);
            }

            _pageSize = AlwaysConvert.ToInt(PageSizeOptions.SelectedValue);
            ProductList.RepeatColumns = Cols;
            if (_pageSize == 0)
            {
                _pageSize = ProductDataSource.AdvancedSearchCount(_keywords, _categoryId, _manufacturerId, true, true, true, 0, 0, false, PageHelper.GetShopByChoices());
            }

            if (!Page.IsPostBack)
            {
                if (ApplicationSettings.Instance.SearchProvider == "LuceneSearchProvider" || ApplicationSettings.Instance.SearchProvider == "SqlFtsSearchProvider")
                {
                    bool sortByRelevance = true;
                    if (!string.IsNullOrEmpty(_keywords))
                    {
                        ISearchProvider      provider = SearchProviderLocator.Locate();
                        LuceneSearchProvider lucene   = provider as LuceneSearchProvider;
                        if (lucene != null)
                        {
                            sortByRelevance = !lucene.UseSQLSearch(_keywords);
                        }
                        SqlFtsSearchProvider sqlFTS = provider as SqlFtsSearchProvider;
                        if (sqlFTS != null)
                        {
                            sortByRelevance = !sqlFTS.UseSQLSearch(_keywords);
                        }
                    }

                    if (sortByRelevance)
                    {
                        SortResults.Items.Insert(0, new ListItem("By Relevance", "FTS.RANK DESC"));
                    }
                }

                //INITIALIZE SEARCH CRITERIA ON FIRST VISIT
                HiddenPageIndex.Value = AlwaysConvert.ToInt(Request.QueryString["p"]).ToString();
                string tempSort = Request.QueryString["s"];
                if (!string.IsNullOrEmpty(tempSort))
                {
                    ListItem item = SortResults.Items.FindByValue(tempSort);
                    if (item != null)
                    {
                        item.Selected = true;
                    }
                }
            }

            int  manufecturerCount      = ManufacturerDataSource.CountAll();
            bool showSortByManufacturer = false;

            if (manufecturerCount > 0 && _manufacturerId == 0)
            {
                IList <ManufacturerProductCount> mCounts = ProductDataSource.AdvancedSearchCountByManufacturer(_keywords, _categoryId, true, true, true, 0, 0, PageHelper.GetShopByChoices());
                showSortByManufacturer = mCounts != null && mCounts.Count > 0;
            }

            foreach (ListItem li in SortResults.Items)
            {
                if (li.Value.StartsWith("Manufacturer"))
                {
                    li.Enabled = showSortByManufacturer;
                }
            }

            BindSearchResultsPanel();
        }
        public override SiteMapNode FindSiteMapNode(string rawUrl)
        {
            //FIRST CHECK WHETHER THIS PAGE IS SPECIFICALLY KEYED IN THE CONFIG FILE
            SiteMapNode baseNode = base.FindSiteMapNode(rawUrl);

            if (baseNode != null)
            {
                if (_EnableHiding)
                {
                    return(FindVisibleNode(baseNode));
                }
                return(baseNode);
            }

            //PAGE NOT FOUND, CHECK WHETHER THIS URL MATCHES KNOWN CMS PAGES
            int categoryId = -1;

            WebTrace.Write(this.GetType().ToString(), "FindSiteMapNode: " + rawUrl + ", Check For CategoryId");
            Match urlMatch = Regex.Match(rawUrl, "(?<baseUrl>.*)\\?(?:.*&)?CategoryId=(?<categoryId>[^&]*)", (RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase));

            if (urlMatch.Success)
            {
                //CATEGORYID PROVIDED IN URL
                categoryId = AlwaysConvert.ToInt(urlMatch.Groups[2].Value);
            }
            else
            {
                WebTrace.Write(this.GetType().ToString(), "FindSiteMapNode: " + rawUrl + ", Check For Catalog Object Id");
                urlMatch = Regex.Match(rawUrl, "(?<baseUrl>.*)\\?(?:.*&)?(?<nodeType>ProductId|WebpageId|LinkId)=(?<catalogId>[^&]*)", (RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase));
                if (urlMatch.Success)
                {
                    string objectType = urlMatch.Groups[2].Value;
                    switch (objectType)
                    {
                    case "ProductId":
                        categoryId = CatalogDataSource.GetCategoryId(AlwaysConvert.ToInt(urlMatch.Groups[3].Value), CatalogNodeType.Product);
                        break;

                    case "WebpageId":
                        categoryId = CatalogDataSource.GetCategoryId(AlwaysConvert.ToInt(urlMatch.Groups[3].Value), CatalogNodeType.Webpage);
                        break;

                    default:
                        categoryId = CatalogDataSource.GetCategoryId(AlwaysConvert.ToInt(urlMatch.Groups[3].Value), CatalogNodeType.Link);
                        break;
                    }
                    WebTrace.Write("Found catalogobjectid, type: " + objectType + ", id: " + categoryId.ToString());
                }
            }

            if (categoryId > -1)
            {
                //FIND BASE NODE
                WebTrace.Write(this.GetType().ToString(), "CategoryId Detected, Find Base Node");
                baseNode = base.FindSiteMapNode(urlMatch.Groups[1].Value);
                if (baseNode != null)
                {
                    WebTrace.Write(this.GetType().ToString(), "Base Node Found, Inject Catalog Path");
                    List <SiteMapNode> pathNodes = this.GetSiteMapPathNodes(baseNode);
                    WebTrace.Write("default pathnodes count: " + pathNodes.Count.ToString());
                    int catalogNodeIndex = this.GetCatalogNodeIndex(pathNodes);
                    //IF CATALOG NODE IS NOT FOUND, RETURN THE BASE NODE FOUND BY PROVIDER
                    if (catalogNodeIndex < 0)
                    {
                        return(baseNode);
                    }
                    WebTrace.Write(this.GetType().ToString(), "Catalog Node Obtained, Building Dynamic Path");
                    //APPEND CMS PATH TO THE
                    List <SiteMapNode> dynamicNodes      = new List <SiteMapNode>();
                    List <CmsPathNode> activeCatalogPath = CmsPath.GetCmsPath(0, categoryId, CatalogNodeType.Category);
                    //IF THERE ARE IS NO PATH INFORMATION BEYOND THE ROOT NODE, RETURN THE BASE NODE FOUND BY PROVIDER
                    if ((activeCatalogPath == null) || (activeCatalogPath.Count < 1))
                    {
                        return(baseNode);
                    }
                    WebTrace.Write("ActivePathCount: " + activeCatalogPath.Count.ToString());
                    for (int i = 0; i < activeCatalogPath.Count; i++)
                    {
                        SiteMapNode newDynamicNode = new SiteMapNode(baseNode.Provider, activeCatalogPath[i].NodeId.ToString(), activeCatalogPath[i].Url, activeCatalogPath[i].Title, activeCatalogPath[i].Description);
                        if (dynamicNodes.Count > 0)
                        {
                            newDynamicNode.ParentNode = dynamicNodes[dynamicNodes.Count - 1];
                        }
                        dynamicNodes.Add(newDynamicNode);
                    }
                    dynamicNodes[0].ParentNode = pathNodes[catalogNodeIndex];
                    if (catalogNodeIndex == pathNodes.Count - 1)
                    {
                        //THERE ARE NO PATH NODES FOLLOWING CATALOG, RETURN LAST DYNAMIC NODE
                        WebTrace.Write("return last dynamic node");
                        return(dynamicNodes[dynamicNodes.Count - 1]);
                    }
                    else
                    {
                        //THERE WERE PATH NODES FOLLOWING CATALOG, UPDATE PARENT TO LAST DYNAMIC NODE
                        WebTrace.Write("append nodes following catalog");
                        //GET NODE THAT SHOULD BE LINKED FROM LAST DYNAMIC PATH NODE
                        //CLONE THE NODE TO PREVENT CACHING, THEN SET PARENT TO DYNAMIC NODE
                        SiteMapNode dynamicNextPathNode = pathNodes[catalogNodeIndex + 1].Clone(false);
                        pathNodes[catalogNodeIndex + 1] = dynamicNextPathNode;
                        dynamicNextPathNode.ReadOnly    = false;
                        dynamicNextPathNode.ParentNode  = dynamicNodes[dynamicNodes.Count - 1];
                        //LOOP THROUGH REMAINING PATH NODES, CLONE THEM AND SET PARENT TO PREVIOUS DYNAMIC NODE
                        for (int i = catalogNodeIndex + 2; i < pathNodes.Count; i++)
                        {
                            dynamicNextPathNode            = pathNodes[i].Clone(false);
                            pathNodes[i]                   = dynamicNextPathNode;
                            dynamicNextPathNode.ReadOnly   = false;
                            dynamicNextPathNode.ParentNode = pathNodes[i - 1];
                        }
                        //NOW RETURN LAST PATH NODE
                        return(pathNodes[pathNodes.Count - 1]);
                    }
                }
            }

            //THIS PATH TO THIS PAGE CANNOT BE DETERMINED
            return(null);
        }
        /// <summary>
        /// Saves this ProductVariant object to the database.
        /// </summary>
        /// <returns><b>SaveResult</b> enumeration that represents the result of the save operation.</returns>
        protected SaveResult BaseSave()
        {
            if (this.IsDirty)
            {
                Database database     = Token.Instance.Database;
                bool     recordExists = true;

                if (this.ProductVariantId == 0)
                {
                    recordExists = false;
                }

                if (recordExists)
                {
                    //verify whether record is already present
                    StringBuilder selectQuery = new StringBuilder();
                    selectQuery.Append("SELECT COUNT(*) As RecordCount FROM ac_ProductVariants");
                    selectQuery.Append(" WHERE ProductVariantId = @productVariantId");
                    using (DbCommand selectCommand = database.GetSqlStringCommand(selectQuery.ToString()))
                    {
                        database.AddInParameter(selectCommand, "@productVariantId", System.Data.DbType.Int32, this.ProductVariantId);
                        if ((int)database.ExecuteScalar(selectCommand) == 0)
                        {
                            recordExists = false;
                        }
                    }
                }

                int result = 0;
                if (recordExists)
                {
                    //UPDATE
                    StringBuilder updateQuery = new StringBuilder();
                    updateQuery.Append("UPDATE ac_ProductVariants SET ");
                    updateQuery.Append("ProductId = @ProductId");
                    updateQuery.Append(", Option1 = @Option1");
                    updateQuery.Append(", Option2 = @Option2");
                    updateQuery.Append(", Option3 = @Option3");
                    updateQuery.Append(", Option4 = @Option4");
                    updateQuery.Append(", Option5 = @Option5");
                    updateQuery.Append(", Option6 = @Option6");
                    updateQuery.Append(", Option7 = @Option7");
                    updateQuery.Append(", Option8 = @Option8");
                    updateQuery.Append(", VariantName = @VariantName");
                    updateQuery.Append(", Sku = @Sku");
                    updateQuery.Append(", Price = @Price");
                    updateQuery.Append(", PriceModeId = @PriceModeId");
                    updateQuery.Append(", Weight = @Weight");
                    updateQuery.Append(", WeightModeId = @WeightModeId");
                    updateQuery.Append(", CostOfGoods = @CostOfGoods");
                    updateQuery.Append(", InStock = @InStock");
                    updateQuery.Append(", InStockWarningLevel = @InStockWarningLevel");
                    updateQuery.Append(", Available = @Available");
                    updateQuery.Append(" WHERE ProductVariantId = @ProductVariantId");
                    using (DbCommand updateCommand = database.GetSqlStringCommand(updateQuery.ToString()))
                    {
                        database.AddInParameter(updateCommand, "@ProductVariantId", System.Data.DbType.Int32, this.ProductVariantId);
                        database.AddInParameter(updateCommand, "@ProductId", System.Data.DbType.Int32, this.ProductId);
                        database.AddInParameter(updateCommand, "@Option1", System.Data.DbType.Int32, this.Option1);
                        database.AddInParameter(updateCommand, "@Option2", System.Data.DbType.Int32, this.Option2);
                        database.AddInParameter(updateCommand, "@Option3", System.Data.DbType.Int32, this.Option3);
                        database.AddInParameter(updateCommand, "@Option4", System.Data.DbType.Int32, this.Option4);
                        database.AddInParameter(updateCommand, "@Option5", System.Data.DbType.Int32, this.Option5);
                        database.AddInParameter(updateCommand, "@Option6", System.Data.DbType.Int32, this.Option6);
                        database.AddInParameter(updateCommand, "@Option7", System.Data.DbType.Int32, this.Option7);
                        database.AddInParameter(updateCommand, "@Option8", System.Data.DbType.Int32, this.Option8);
                        database.AddInParameter(updateCommand, "@VariantName", System.Data.DbType.String, NullableData.DbNullify(this.VariantName));
                        database.AddInParameter(updateCommand, "@Sku", System.Data.DbType.String, NullableData.DbNullify(this.Sku));
                        database.AddInParameter(updateCommand, "@Price", System.Data.DbType.Decimal, NullableData.DbNullify(this.Price));
                        database.AddInParameter(updateCommand, "@PriceModeId", System.Data.DbType.Byte, this.PriceModeId);
                        database.AddInParameter(updateCommand, "@Weight", System.Data.DbType.Decimal, NullableData.DbNullify(this.Weight));
                        database.AddInParameter(updateCommand, "@WeightModeId", System.Data.DbType.Byte, this.WeightModeId);
                        database.AddInParameter(updateCommand, "@CostOfGoods", System.Data.DbType.Decimal, NullableData.DbNullify(this.CostOfGoods));
                        database.AddInParameter(updateCommand, "@InStock", System.Data.DbType.Int32, this.InStock);
                        database.AddInParameter(updateCommand, "@InStockWarningLevel", System.Data.DbType.Int32, this.InStockWarningLevel);
                        database.AddInParameter(updateCommand, "@Available", System.Data.DbType.Boolean, this.Available);
                        //RESULT IS NUMBER OF RECORDS AFFECTED
                        result = database.ExecuteNonQuery(updateCommand);
                    }
                }
                else
                {
                    //INSERT
                    StringBuilder insertQuery = new StringBuilder();
                    insertQuery.Append("INSERT INTO ac_ProductVariants (ProductId, Option1, Option2, Option3, Option4, Option5, Option6, Option7, Option8, VariantName, Sku, Price, PriceModeId, Weight, WeightModeId, CostOfGoods, InStock, InStockWarningLevel, Available)");
                    insertQuery.Append(" VALUES (@ProductId, @Option1, @Option2, @Option3, @Option4, @Option5, @Option6, @Option7, @Option8, @VariantName, @Sku, @Price, @PriceModeId, @Weight, @WeightModeId, @CostOfGoods, @InStock, @InStockWarningLevel, @Available)");
                    insertQuery.Append("; SELECT Scope_Identity()");
                    using (DbCommand insertCommand = database.GetSqlStringCommand(insertQuery.ToString()))
                    {
                        database.AddInParameter(insertCommand, "@ProductVariantId", System.Data.DbType.Int32, this.ProductVariantId);
                        database.AddInParameter(insertCommand, "@ProductId", System.Data.DbType.Int32, this.ProductId);
                        database.AddInParameter(insertCommand, "@Option1", System.Data.DbType.Int32, this.Option1);
                        database.AddInParameter(insertCommand, "@Option2", System.Data.DbType.Int32, this.Option2);
                        database.AddInParameter(insertCommand, "@Option3", System.Data.DbType.Int32, this.Option3);
                        database.AddInParameter(insertCommand, "@Option4", System.Data.DbType.Int32, this.Option4);
                        database.AddInParameter(insertCommand, "@Option5", System.Data.DbType.Int32, this.Option5);
                        database.AddInParameter(insertCommand, "@Option6", System.Data.DbType.Int32, this.Option6);
                        database.AddInParameter(insertCommand, "@Option7", System.Data.DbType.Int32, this.Option7);
                        database.AddInParameter(insertCommand, "@Option8", System.Data.DbType.Int32, this.Option8);
                        database.AddInParameter(insertCommand, "@VariantName", System.Data.DbType.String, NullableData.DbNullify(this.VariantName));
                        database.AddInParameter(insertCommand, "@Sku", System.Data.DbType.String, NullableData.DbNullify(this.Sku));
                        database.AddInParameter(insertCommand, "@Price", System.Data.DbType.Decimal, NullableData.DbNullify(this.Price));
                        database.AddInParameter(insertCommand, "@PriceModeId", System.Data.DbType.Byte, this.PriceModeId);
                        database.AddInParameter(insertCommand, "@Weight", System.Data.DbType.Decimal, NullableData.DbNullify(this.Weight));
                        database.AddInParameter(insertCommand, "@WeightModeId", System.Data.DbType.Byte, this.WeightModeId);
                        database.AddInParameter(insertCommand, "@CostOfGoods", System.Data.DbType.Decimal, NullableData.DbNullify(this.CostOfGoods));
                        database.AddInParameter(insertCommand, "@InStock", System.Data.DbType.Int32, this.InStock);
                        database.AddInParameter(insertCommand, "@InStockWarningLevel", System.Data.DbType.Int32, this.InStockWarningLevel);
                        database.AddInParameter(insertCommand, "@Available", System.Data.DbType.Boolean, this.Available);
                        //RESULT IS NEW IDENTITY;
                        result = AlwaysConvert.ToInt(database.ExecuteScalar(insertCommand));
                        this._ProductVariantId = result;
                    }
                }

                //OBJECT IS DIRTY IF NO RECORDS WERE UPDATED OR INSERTED
                this.IsDirty = (result == 0);
                if (this.IsDirty)
                {
                    return(SaveResult.Failed);
                }
                else
                {
                    return(recordExists ? SaveResult.RecordUpdated : SaveResult.RecordInserted);
                }
            }

            //SAVE IS SUCCESSFUL IF OBJECT IS NOT DIRTY
            return(SaveResult.NotDirty);
        }
Esempio n. 26
0
        public void ProcessRequest(HttpContext context)
        {
            //GET REFERENCE TO REQUEST
            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;
            TraceContext trace    = context.Trace;

            //RECORD FORM VALUES TO TRACE OUTPUT
            foreach (string key in request.Form)
            {
                context.Trace.Write(key + ":" + request.Form[key]);
            }
            //SETUP DEFAULT REDIRECT URL
            string redirectUrl = "~/Default.aspx";
            //INITIALIZE THE PAYPAL PROVIDER
            PaymentGateway paypalGateway = PayPalProvider.GetPayPalPaymentGateway(true);

            if (paypalGateway == null)
            {
                response.Redirect(redirectUrl);
            }
            //LOOK FOR ORDER ID
            int    orderId;
            string customValue = request.Form["custom"];

            if (!String.IsNullOrEmpty(customValue))
            {
                int index = customValue.IndexOf(":");
                if (index > 0)
                {
                    orderId = AlwaysConvert.ToInt(customValue.Substring(0, index));
                }
                else
                {
                    orderId = AlwaysConvert.ToInt(customValue);
                }
            }
            else
            {
                // TRY TO LOCATE ORDER ID AS QUERY STRING PARAMETER
                orderId = AlwaysConvert.ToInt(request.QueryString["OrderId"]);
            }

            //IF ORDER ID WAS NOT IN CUSTOM, SEE IF WE CAN FIND THE ORDER VIA TRANSACTION ID
            if (orderId == 0)
            {
                trace.Write("OrderId not found in custom field; lookup via transaction ID");
                string parentTransactionId = IpnProcessor.GetFormValue(request.Form, "parent_txn_id");
                if (!string.IsNullOrEmpty(parentTransactionId) && (paypalGateway != null))
                {
                    trace.Write("Query for parent transaction " + parentTransactionId);
                    orderId = FindPayPalOrderId(paypalGateway.PaymentGatewayId, parentTransactionId);
                    if (orderId != 0)
                    {
                        trace.Write("Order ID Found: " + orderId.ToString());
                    }
                }
            }
            //TRY TO LOAD ORDER
            Order order = OrderDataSource.Load(orderId);

            //IF ORDER LOAD FAILS, STOP PROCESSING AND REDIRECT
            if (order == null)
            {
                response.Redirect(redirectUrl);
            }
            //ORDER LOAD SUCCESSFUL, UPDATE DEFAULT REDIRECT URL
            redirectUrl = "~/Members/MyOrder.aspx?OrderId=" + orderId.ToString();
            //IF GATEWAY NOT FOUND, STOP PROCESSING AND REDIRECT
            PayPalProvider provider = (PayPalProvider)paypalGateway.GetInstance();
            //GET TRANSACTION AMOUNT
            LSDecimal curSignedPayment = AlwaysConvert.ToDecimal(request.Form["mc_gross"]);
            LSDecimal curPayment       = Math.Abs((Decimal)curSignedPayment);

            context.Trace.Write("Transaction Amount is " + curPayment.ToString());
            if (curPayment != 0)
            {
                //VERIFY PAYMENT NOTIFICATION WITH PAYPAL
                bool valid = provider.ValidateNotification(request.Form.ToString());
                if (!valid)
                {
                    response.Redirect(redirectUrl);
                }
                //VERIFY THE RECEIVER EMAIL
                string lowerReceiverEmail   = AlwaysConvert.ToString(request.Form["receiver_email"]).ToLowerInvariant();
                string lowerProviderAccount = provider.PayPalAccount.ToLowerInvariant();
                if (lowerReceiverEmail != lowerProviderAccount)
                {
                    context.Trace.Write("Receiver Email (" + lowerReceiverEmail + ") does not match Primary Account (" + lowerProviderAccount + ")");
                    response.Redirect(redirectUrl);
                }
                //CHECK WHETHER TRANSACTION IS ALREADY PRESENT IN DATABASE
                string paypalTransactionId = IpnProcessor.GetFormValue(request.Form, "txn_id");
                string authTransactionId   = IpnProcessor.GetFormValue(request.Form, "auth_id");
                string paymentStatus       = IpnProcessor.GetFormValue(request.Form, "payment_status").ToUpperInvariant();
                string authStatus          = IpnProcessor.GetFormValue(request.Form, "auth_status").ToUpperInvariant();
                context.Trace.Write("Transaction ID Is " + paypalTransactionId);
                context.Trace.Write("Payment Status Is " + paymentStatus);
                context.Trace.Write("Auth Status Is " + authStatus);

                //CHECK FOR THIS PAYPAL TRANSACTION (MATCHING PROVIDER, PAYPAL TRANSACTION ID, AND PAYMENT STATUS)
                Payment     payment            = null;
                Transaction pendingTransaction = null;
                if (!string.IsNullOrEmpty(paypalTransactionId))
                {
                    TransactionCollection matchingTransactions = TransactionDataSource.LoadForProviderTransaction(paypalGateway.PaymentGatewayId, paypalTransactionId);
                    foreach (Transaction tx in matchingTransactions)
                    {
                        //WHEN PAYMENT IS BY ECHECK, IPN ISSUES A PENDING TRANSACTION
                        //SECOND IPN COMES FOR COMPLETED STATUS USING SAME TRANSACTION ID
                        if ((tx.ResponseCode == "PENDING") && (paymentStatus != "PENDING"))
                        {
                            //WE HAVE TO GET THE TRANSACTION VIA THE PAYMENT OBJECT
                            //OTHERWISE WE WILL HAVE PROBLEMS WITH DATA CONSISTENCY LATER
                            payment = tx.Payment;
                            foreach (Transaction ptx in payment.Transactions)
                            {
                                if (ptx.TransactionId == tx.TransactionId)
                                {
                                    pendingTransaction = ptx;
                                }
                            }
                        }
                        else if ((tx.TransactionType != TransactionType.Void) && (paymentStatus == "VOIDED"))
                        {
                            //IF WE VOID AN AUTHORIZATION, THE VOID HAS THE SAME TXID
                            //THE AUTHORIZATION WILL HAVE A BLANK RESPONSE CODE
                            //THE VOID SHOULD HAVE A 'VOIDED' RESPONSE CODE
                            //(THIS TRANSACTION IS NOT A MATCH AND SHOULD BE IGNORED)
                        }
                        else
                        {
                            //NO FURTHER PROCESSING, REDIR TO ORDER SCREEN
                            context.Trace.Write("Transaction ID " + paypalTransactionId + " Already Exists in Database");
                            response.Redirect(redirectUrl);
                        }
                    }
                }

                Transaction       transaction       = null;
                PaymentMethod     paypalMethod      = PayPalProvider.GetPayPalPaymentMethod(true);
                PaymentCollection orderPayments     = order.Payments;
                Transaction       authTransaction   = null;
                PaymentStatus[]   validAuthStatuses = { PaymentStatus.Unprocessed, PaymentStatus.AuthorizationPending };
                context.Trace.Write("Processing Payment Status: " + paymentStatus);
                switch (paymentStatus)
                {
                case "PENDING":
                    //THIS IS A PENDING TRANSACTION, GET PENDING REASON AND FIND OUT IF IT IS AN ECHECK WAITING TO CLEAR
                    string pendingReason          = IpnProcessor.GetFormValue(request.Form, "pending_reason").ToLowerInvariant();
                    bool   isPendingeCheck        = (pendingReason == "echeck");
                    bool   isPendingAuthorization = (pendingReason == "authorization");
                    context.Trace.Write("Pending Reason: " + pendingReason);
                    context.Trace.Write("Is Pending eCheck: " + isPendingeCheck.ToString());
                    context.Trace.Write("Is Pending Authorization: " + isPendingAuthorization.ToString());
                    //FIND THE PAYPAL PAYMENT THAT IS UNPROCESSED OR PENDING AUTHORIZATION
                    payment = FindPaypalPayment(paypalMethod.PaymentMethodId, orderPayments, validAuthStatuses);
                    if (payment != null)
                    {
                        //SEE IF WE CAN FIND A PENDING PAYPAL TRANSACTION WITHOUT A TXID
                        foreach (Transaction tx in payment.Transactions)
                        {
                            if ((tx.ResponseCode == "PENDING") && string.IsNullOrEmpty(tx.ProviderTransactionId))
                            {
                                transaction = tx;
                            }
                        }
                    }
                    //IF WE DID NOT FIND AN EXISTING TRANSACTION, CREATE A NEW ONE
                    if (transaction == null)
                    {
                        transaction = new Transaction();
                    }
                    //UPDATE THE TRANSACTION VALUES
                    transaction.TransactionType       = (isPendingeCheck ? TransactionType.Capture : TransactionType.Authorize);
                    transaction.PaymentGatewayId      = paypalGateway.PaymentGatewayId;
                    transaction.ProviderTransactionId = IpnProcessor.GetFormValue(request.Form, "txn_id");
                    transaction.TransactionDate       = AlwaysConvert.ToDateTime(request.Form["payment_date"], DateTime.UtcNow).ToUniversalTime();
                    transaction.Amount            = AlwaysConvert.ToDecimal(IpnProcessor.GetFormValue(request.Form, "mc_gross"));
                    transaction.TransactionStatus = TransactionStatus.Successful;
                    if (isPendingAuthorization)
                    {
                        //THIS IS AN EXPECTED RESPONSE, NO NEED TO SAVE THE REASON CODES
                        transaction.ResponseMessage = string.Empty;
                        transaction.ResponseCode    = string.Empty;
                    }
                    else
                    {
                        transaction.ResponseMessage = pendingReason;
                        transaction.ResponseCode    = "PENDING";
                    }
                    transaction.AuthorizationCode = IpnProcessor.GetFormValue(request.Form, "auth_id");
                    transaction.RemoteIP          = IpnProcessor.GetFormValue(request.ServerVariables, "REMOTE_ADDR");
                    transaction.Referrer          = IpnProcessor.GetFormValue(request.ServerVariables, "HTTP_REFERER");
                    //CREATE A PAYMENT IF AN EXISTING ONE WAS NOT FOUND
                    if (payment == null)
                    {
                        payment                   = new Payment();
                        payment.OrderId           = orderId;
                        payment.PaymentMethodId   = paypalMethod.PaymentMethodId;
                        payment.PaymentMethodName = paypalMethod.Name;
                        order.Payments.Add(payment);
                    }
                    //UPDATE PAYMENT DETAILS
                    payment.ReferenceNumber = IpnProcessor.GetFormValue(request.Form, "payer_email");
                    payment.Amount          = transaction.Amount;
                    payment.PaymentDate     = transaction.TransactionDate;
                    if (isPendingAuthorization)
                    {
                        payment.PaymentStatus       = PaymentStatus.Authorized;
                        payment.PaymentStatusReason = string.Empty;
                    }
                    else
                    {
                        payment.PaymentStatus       = (isPendingeCheck ? PaymentStatus.CapturePending : PaymentStatus.AuthorizationPending);
                        payment.PaymentStatusReason = transaction.ResponseMessage;
                    }
                    //ADD IN TRANSACTION
                    payment.Transactions.Add(transaction);
                    break;

                case "COMPLETED":
                    //IF THIS IS A CAPTURE FROM AN AUTHORIZATION, FIND THE AUTHORIZATION TRANSACTION
                    //AND UPDATE THE STATUS ACCORDINGLY, DEPENDING ON WHETHER ADDITIONAL SETTLEMENT TRANSACTIONS REMAIN (INTREMSETTLE > 0)
                    authTransaction   = null;
                    authTransactionId = IpnProcessor.GetFormValue(request.Form, "auth_id");
                    if (!string.IsNullOrEmpty(authTransactionId))
                    {
                        TransactionCollection matchingTransactions = TransactionDataSource.LoadForProviderTransaction(paypalGateway.PaymentGatewayId, authTransactionId);
                        //SHOULD ONLY BE ONE
                        if (matchingTransactions.Count > 0)
                        {
                            authTransaction = matchingTransactions[0];
                        }
                    }
                    //IF PAYPAL IS RUNNING IN CAPTURE MODE, WE MAY HAVE A COMPLETED PAYMENT
                    //WITH A PENDING OR UNPROCESSED PAYMENT ALREADY ASSOCIATED TO ORDER
                    if (pendingTransaction == null)
                    {
                        //FIND THE PAYPAL PAYMENT THAT IS UNPROCESSED OR PENDING
                        payment = FindPaypalPayment(paypalMethod.PaymentMethodId, orderPayments, validAuthStatuses);
                        if (payment != null)
                        {
                            //SEE IF WE CAN FIND A PENDING PAYPAL TRANSACTION WITHOUT A TXID
                            foreach (Transaction tx in payment.Transactions)
                            {
                                if ((tx.ResponseCode == "PENDING") && string.IsNullOrEmpty(tx.ProviderTransactionId))
                                {
                                    pendingTransaction = tx;
                                }
                            }
                        }
                    }
                    //SEE IF THIS TRANSACTION WAS PENDING (SUCH AS A CHECK WAITING TO CLEAR)
                    if (pendingTransaction != null)
                    {
                        //GET THE PENDING TRANSACTION AND PAYMENT
                        payment     = order.Payments[order.Payments.IndexOf(pendingTransaction.PaymentId)];
                        transaction = payment.Transactions[payment.Transactions.IndexOf(pendingTransaction.TransactionId)];
                    }
                    else
                    {
                        //THIS IS NOT A PENDING TRANSACTION
                        //LOCATE THE APPROPRIATE PAYMENT
                        if (authTransaction != null)
                        {
                            payment = order.Payments[order.Payments.IndexOf(authTransaction.PaymentId)];
                        }
                        else
                        {
                            //FIND THE PAYPAL PAYMENT THAT CAN BE CAPTURED
                            PaymentStatus[] validCaptureStatuses = { PaymentStatus.Unprocessed, PaymentStatus.AuthorizationPending, PaymentStatus.Authorized, PaymentStatus.CaptureFailed, PaymentStatus.CapturePending };
                            payment = FindPaypalPayment(paypalMethod.PaymentMethodId, orderPayments, validCaptureStatuses);
                            //CREATE A PAYMENT IF AN EXISTING ONE WAS NOT FOUND
                            if (payment == null)
                            {
                                payment                   = new Payment();
                                payment.OrderId           = orderId;
                                payment.PaymentMethodId   = paypalMethod.PaymentMethodId;
                                payment.PaymentMethodName = paypalMethod.Name;
                                order.Payments.Add(payment);
                            }
                        }
                        //CREATE A NEW TRANSACTION RECORD
                        transaction           = new Transaction();
                        transaction.PaymentId = payment.PaymentId;
                    }
                    //UPDATE THE TRANSACTION DETAILS
                    transaction.TransactionType       = TransactionType.Capture;
                    transaction.PaymentGatewayId      = paypalGateway.PaymentGatewayId;
                    transaction.TransactionDate       = AlwaysConvert.ToDateTime(request.Form["payment_date"], DateTime.UtcNow).ToUniversalTime();
                    transaction.RemoteIP              = IpnProcessor.GetFormValue(request.ServerVariables, "REMOTE_ADDR");
                    transaction.Referrer              = IpnProcessor.GetFormValue(request.ServerVariables, "HTTP_REFERER");
                    transaction.TransactionStatus     = TransactionStatus.Successful;
                    transaction.ProviderTransactionId = IpnProcessor.GetFormValue(request.Form, "txn_id");
                    transaction.AuthorizationCode     = IpnProcessor.GetFormValue(request.Form, "auth_id");
                    transaction.Amount          = AlwaysConvert.ToDecimal(IpnProcessor.GetFormValue(request.Form, "mc_gross"));
                    transaction.ResponseCode    = paymentStatus;
                    transaction.ResponseMessage = string.Empty;

                    //HANDLE PARTIAL / FINAL CAPTURES
                    int remainingSettle = AlwaysConvert.ToInt(IpnProcessor.GetFormValue(request.Form, "remaining_settle"));
                    if (remainingSettle == 0)
                    {
                        //THIS IS A FINAL CAPTURE
                        transaction.TransactionType = TransactionType.Capture;
                        //SET PAYMENT AMOUNT TO SUM OF ALL CAPTURES
                        LSDecimal totalCaptures = 0;
                        foreach (Transaction tx in payment.Transactions)
                        {
                            if ((transaction.TransactionId != tx.TransactionId) &&
                                (tx.TransactionType == TransactionType.PartialCapture || tx.TransactionType == TransactionType.Capture))
                            {
                                totalCaptures += tx.Amount;
                            }
                        }
                        totalCaptures += transaction.Amount;
                        payment.Amount = totalCaptures;
                    }
                    else
                    {
                        //THIS IS A PARTIAL CAPTURE
                        transaction.TransactionType = TransactionType.PartialCapture;
                        //LEAVE PAYMENT AMOUNT ALONE (AMOUNT OF AUTHORIZATION)
                    }

                    //UPDATE PAYMENT DETAILS
                    payment.PaymentDate         = transaction.TransactionDate;
                    payment.PaymentStatus       = (remainingSettle == 0) ? PaymentStatus.Captured : PaymentStatus.Authorized;
                    payment.PaymentStatusReason = string.Empty;

                    //ADD IN TRANSACTION IF NEEDED
                    if (transaction.TransactionId == 0)
                    {
                        payment.Transactions.Add(transaction);
                    }
                    break;

                case "REFUNDED":
                case "REVERSED":
                    //GET THE REFUND AMOUNT
                    LSDecimal refundAmount = Math.Abs(AlwaysConvert.ToDecimal(IpnProcessor.GetFormValue(request.Form, "mc_gross")));
                    //TRY TO LOCATE THE CORRECT PAYMENT BASED ON CAPTURE TRANSACITON ID
                    payment = FindPayPalPayment(paypalGateway.PaymentGatewayId, orderPayments, IpnProcessor.GetFormValue(request.Form, "parent_txn_id"));
                    if (payment == null)
                    {
                        //SEE IF WE CAN FIND THE PAYMENT VIA AUTH TRANSACTION ID
                        payment = FindPayPalPayment(paypalGateway.PaymentGatewayId, orderPayments, IpnProcessor.GetFormValue(request.Form, "auth_id"));
                    }
                    //CREATE A REFUND TRANSACTION
                    transaction = new Transaction();
                    //CREATE A PAYMENT IF AN EXISTING ONE WAS NOT FOUND
                    if (payment == null)
                    {
                        payment                     = new Payment();
                        payment.OrderId             = orderId;
                        payment.PaymentMethodId     = paypalMethod.PaymentMethodId;
                        payment.PaymentMethodName   = paypalMethod.Name;
                        payment.Amount              = -1 * refundAmount;
                        transaction.TransactionType = TransactionType.Refund;
                        order.Payments.Add(payment);
                    }
                    else
                    {
                        if (payment.Amount == refundAmount)
                        {
                            //FULL REFUND
                            transaction.TransactionType = TransactionType.Refund;
                            payment.PaymentStatus       = PaymentStatus.Refunded;
                        }
                        else
                        {
                            //PARTIAL REFUND
                            transaction.TransactionType = TransactionType.PartialRefund;
                            payment.Amount       -= refundAmount;
                            payment.PaymentStatus = PaymentStatus.Captured;
                        }
                    }
                    transaction.PaymentGatewayId      = paypalGateway.PaymentGatewayId;
                    transaction.ProviderTransactionId = IpnProcessor.GetFormValue(request.Form, "txn_id");
                    transaction.TransactionDate       = AlwaysConvert.ToDateTime(request.Form["payment_date"], DateTime.UtcNow).ToUniversalTime();
                    transaction.TransactionStatus     = TransactionStatus.Successful;
                    transaction.AuthorizationCode     = IpnProcessor.GetFormValue(request.Form, "auth_id");
                    transaction.RemoteIP = IpnProcessor.GetFormValue(request.ServerVariables, "REMOTE_ADDR");
                    transaction.Referrer = IpnProcessor.GetFormValue(request.ServerVariables, "HTTP_REFERER");
                    transaction.Amount   = refundAmount;
                    string responseMessage = IpnProcessor.GetFormValue(request.Form, "reason_code");
                    if (responseMessage != "refund")
                    {
                        transaction.ResponseCode    = paymentStatus;
                        transaction.ResponseMessage = responseMessage;
                    }
                    //UPDATE PAYMENT DETAILS
                    payment.PaymentDate         = transaction.TransactionDate;
                    payment.PaymentStatusReason = string.Empty;
                    //ADD IN TRANSACTION
                    payment.Transactions.Add(transaction);
                    break;

                case "VOIDED":
                    //SEE IF WE CAN FIND THE PAYMENT VIA AUTH TRANSACTION ID
                    payment = FindPayPalPayment(paypalGateway.PaymentGatewayId, orderPayments, IpnProcessor.GetFormValue(request.Form, "auth_id"));
                    //WE ONLY NEED TO CONTINUE IF A PAYMENT TO VOID WAS FOUND
                    if (payment != null)
                    {
                        //PAYPAL DOES NOT SEND THE AMOUNT OF THE VOID
                        //SO IF THIS PAYMENT WAS PARTIALLY CAPTURED, WE NEED TO KNOW HOW MUCH TO VOID
                        LSDecimal remainingAuthorization = payment.Transactions.GetRemainingAuthorized();
                        if (remainingAuthorization > 0)
                        {
                            //CREATE A VOID TRANSACTION
                            transaction = new Transaction();
                            transaction.TransactionType       = TransactionType.Void;
                            transaction.Amount                = remainingAuthorization;
                            transaction.PaymentGatewayId      = paypalGateway.PaymentGatewayId;
                            transaction.ProviderTransactionId = IpnProcessor.GetFormValue(request.Form, "txn_id");
                            transaction.TransactionDate       = AlwaysConvert.ToDateTime(request.Form["payment_date"], DateTime.UtcNow).ToUniversalTime();
                            transaction.TransactionStatus     = TransactionStatus.Successful;
                            transaction.AuthorizationCode     = IpnProcessor.GetFormValue(request.Form, "auth_id");
                            transaction.RemoteIP              = IpnProcessor.GetFormValue(request.ServerVariables, "REMOTE_ADDR");
                            transaction.Referrer              = IpnProcessor.GetFormValue(request.ServerVariables, "HTTP_REFERER");
                            //UPDATE PAYMENT DETAILS
                            payment.PaymentDate         = transaction.TransactionDate;
                            payment.PaymentStatusReason = string.Empty;
                            if (payment.Amount == remainingAuthorization)
                            {
                                //FULL VOID, CHANGE PAYMENT STATUS TO VOID
                                payment.PaymentStatus = PaymentStatus.Void;
                            }
                            else
                            {
                                //PARTIAL VOID, REDUCE PAYMENT AMOUNT BY VOID
                                payment.Amount -= remainingAuthorization;
                                //PAYMENT HAS NO REMAINING AUTHORIZATION AND SO IT IS CAPTURED
                                payment.PaymentStatus = PaymentStatus.Captured;
                            }
                            //ADD IN TRANSACTION
                            payment.Transactions.Add(transaction);
                        }
                    }
                    break;

                case "FAILED":
                    //THIS IS A FAILED E-CHECK
                    //PENDINGTRANSACTION SHOULD HAVE BEEN OBTAINED ABOVE
                    if (payment != null && pendingTransaction != null)
                    {
                        pendingTransaction.TransactionStatus = TransactionStatus.Failed;
                        //MAKE SURE TO CLEAR OUT PENDING RESPONSECODE
                        pendingTransaction.ResponseCode = string.Empty;
                        //GET THE CURRENT TRANSACTION DATE
                        pendingTransaction.TransactionDate = AlwaysConvert.ToDateTime(request.Form["payment_date"], DateTime.UtcNow).ToUniversalTime();
                        //UPDATE PAYMENT DETAILS
                        payment.PaymentDate         = pendingTransaction.TransactionDate;
                        payment.PaymentStatus       = (IsVoidableFailure(payment) ? PaymentStatus.Void : PaymentStatus.CaptureFailed);
                        payment.PaymentStatusReason = string.Empty;
                        //SAVE PAYMENT (AND CHILD TRANSACTIONS)
                        payment.Save();
                    }
                    break;

                default:
                    Logger.Warn("PayPal IPN transaction " + paypalTransactionId + " with a \"" + paymentStatus + "\" status was unhandled.");
                    break;
                }

                //IF PAYMENT IS SET, SAVE UPDATES
                if (payment != null)
                {
                    payment.Save();
                }
            }
            response.Redirect(redirectUrl);
        }
Esempio n. 27
0
        protected void Page_Init(object sender, EventArgs e)
        {
            int shipmentId = AlwaysConvert.ToInt(Request.QueryString["OrderShipmentId"]);

            _OrderShipment = OrderShipmentDataSource.Load(shipmentId);
            if (_OrderShipment == null)
            {
                Response.Redirect("../Default.aspx");
            }
            _Order                   = _OrderShipment.Order;
            Caption.Text             = string.Format(Caption.Text, _Order.OrderNumber);
            ShipmentNumber.Text      = string.Format(ShipmentNumber.Text, _Order.Shipments.IndexOf(_OrderShipment.Id) + 1, _Order.Shipments.Count);
            ShippingMethod.Text      = _OrderShipment.ShipMethodName;
            trShipMessage.Visible    = !string.IsNullOrEmpty(_OrderShipment.ShipMessage);
            ShipMessage.Text         = _OrderShipment.ShipMessage;
            ShipFrom.Text            = _OrderShipment.FormatFromAddress();
            ShipTo.Text              = _OrderShipment.FormatToAddress();
            ShipmentItems.DataSource = GetShipmentItems();
            ShipmentItems.DataBind();

            // check if ship gateway supports shipping feature
            CommerceBuilder.Shipping.ShipGateway shipGateway = _OrderShipment.ShipMethod != null ?_OrderShipment.ShipMethod.ShipGateway : null;
            IShippingProvider shipProvider = null;

            if (shipGateway != null)
            {
                shipProvider = shipGateway.GetProviderInstance();
                _IsProviderSupportShipping = shipProvider != null && shipProvider.IsShippingSupported;
            }

            ShipGateway.DataSource = ShipGatewayDataSource.LoadAll();
            ShipGateway.DataBind();
            if (ShipGateway.Items.Count > 1)
            {
                //TRY TO PRESET THE CORRECT GATEWAY
                if (_OrderShipment.ShipMethod != null)
                {
                    ListItem item = ShipGateway.Items.FindByValue(_OrderShipment.ShipMethod.ShipGatewayId.ToString());
                    if (item != null)
                    {
                        item.Selected = true;
                    }
                }
            }
            else
            {
                ShipGateway.Visible = false;
            }

            if (_IsProviderSupportShipping)
            {
                autoTrackingInputPanel.Visible = true;

                // update the provider name
                ProviderInstructionText.Text    = string.Format(ProviderInstructionText.Text, shipProvider.Name);
                ProviderInstructionText.Visible = true;
            }
            else
            {
                autoTrackingInputPanel.Visible = false;
            }

            CancelButton.NavigateUrl += "?OrderNumber=" + _OrderShipment.Order.OrderNumber.ToString();
        }
Esempio n. 28
0
        protected int SaveCoupon()
        {
            if (Page.IsValid)
            {
                // VALIDATE IF A PROPER END DATE IS SELECTED
                if (EndDate.SelectedEndDate != DateTime.MinValue && DateTime.Compare(EndDate.SelectedEndDate, StartDate.SelectedEndDate) < 0)
                {
                    CustomValidator dateValidator = new CustomValidator();
                    dateValidator.ControlToValidate = "Name"; // THIS SHOULD BE "EndDate" CONTROL, BUT THAT CANNOT BE VALIDATED
                    dateValidator.Text         = "*";
                    dateValidator.ErrorMessage = "End date can not be earlier than start date.";
                    dateValidator.IsValid      = false;
                    phEndDateValidator.Controls.Add(dateValidator);
                    return(0);
                }

                Coupon existingCoupon = CouponDataSource.LoadForCouponCode(CouponCode.Text);
                if (existingCoupon != null)
                {
                    CustomValidator codeValidator = new CustomValidator();
                    codeValidator.ControlToValidate = "CouponCode";
                    codeValidator.Text         = "*";
                    codeValidator.ErrorMessage = "The coupon code " + CouponCode.Text + " is already in use.";
                    codeValidator.IsValid      = false;
                    phCouponCodeValidator.Controls.Add(codeValidator);
                    return(0);
                }

                Coupon _Coupon = new Coupon();
                _Coupon.CouponType     = this.CouponType;
                _Coupon.Name           = Name.Text;
                _Coupon.CouponCode     = CouponCode.Text;
                _Coupon.DiscountAmount = AlwaysConvert.ToDecimal(DiscountAmount.Text);
                _Coupon.IsPercent      = (DiscountType.SelectedIndex == 0);
                //QUANTITY SETTINGS (PRODUCT COUPON)
                if (_Coupon.CouponType == CouponType.Product)
                {
                    _Coupon.MinQuantity = AlwaysConvert.ToInt16(Quantity.Text);
                    if (RepeatCoupon.Checked)
                    {
                        _Coupon.MaxQuantity      = 0;
                        _Coupon.QuantityInterval = _Coupon.MinQuantity;
                    }
                    else
                    {
                        _Coupon.MaxQuantity      = _Coupon.MinQuantity;
                        _Coupon.QuantityInterval = 0;
                    }
                    _Coupon.MaxValue    = 0;
                    _Coupon.MinPurchase = 0;
                }
                //PURCHASE RESTRICTIONS (ORDER AND SHIPPING COUPONS)
                else
                {
                    _Coupon.MaxValue         = AlwaysConvert.ToDecimal(MaxValue.Text);
                    _Coupon.MinPurchase      = AlwaysConvert.ToDecimal(MinPurchase.Text);
                    _Coupon.MinQuantity      = 0;
                    _Coupon.MaxQuantity      = 0;
                    _Coupon.QuantityInterval = 0;
                }
                //SET START DATE
                _Coupon.StartDate = StartDate.SelectedDate;
                //SET END DATE
                _Coupon.EndDate = EndDate.SelectedEndDate;
                //MAX USES
                _Coupon.MaxUsesPerCustomer = AlwaysConvert.ToInt16(MaximumUsesPerCustomer.Text);
                _Coupon.MaxUses            = AlwaysConvert.ToInt16(MaximumUses.Text);
                //COMBINE RULE
                _Coupon.AllowCombine = AllowCombine.Checked;
                //PRODUCT (OR SHIPPING) RULE
                if (_Coupon.CouponType != CouponType.Shipping)
                {
                    _Coupon.ProductRule = (CouponRule)ProductRule.SelectedIndex;
                }
                else
                {
                    _Coupon.ProductRule = (CouponRule)ShipMethodRule.SelectedIndex;
                    _Coupon.ShipMethods.Clear();
                    _Coupon.Save();
                    if (_Coupon.ProductRule != CouponRule.All)
                    {
                        foreach (ListItem item in ShipMethodList.Items)
                        {
                            ShipMethod shipMethod = ShipMethodDataSource.Load(AlwaysConvert.ToInt(item.Value));
                            if (item.Selected)
                            {
                                _Coupon.ShipMethods.Add(shipMethod);
                            }
                        }
                    }
                }
                //GROUP RESTRICTION
                if (UseGroupRestriction.SelectedIndex > 0)
                {
                    _Coupon.Groups.Clear();
                    _Coupon.Save();
                    foreach (ListItem item in GroupList.Items)
                    {
                        Group group = GroupDataSource.Load(AlwaysConvert.ToInt(item.Value));
                        if (item.Selected)
                        {
                            _Coupon.Groups.Add(group);
                        }
                    }
                }
                _Coupon.Save();
                return(_Coupon.Id);
            }
            return(0);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            _UserId = AlwaysConvert.ToInt(Request.QueryString["UserId"]);
            List <PurchaseSummary> paidItems = (List <PurchaseSummary>)PaidOrdersDs.Select();

            paidItems.Sort(new PurchaseSummaryComparer(SortDirection.Ascending));

            List <PurchaseSummary> unpaidItems = (List <PurchaseSummary>)UnpaidOrdersDs.Select();

            unpaidItems.Sort(new PurchaseSummaryComparer(SortDirection.Ascending));

            DateTime firstOrderDate = DateTime.MinValue;

            if (paidItems.Count > 0)
            {
                firstOrderDate = paidItems[0].OrderDate;
            }
            if (unpaidItems.Count > 0)
            {
                if (firstOrderDate == DateTime.MinValue || unpaidItems[0].OrderDate < firstOrderDate)
                {
                    firstOrderDate = unpaidItems[0].OrderDate;
                }
            }

            if (firstOrderDate != DateTime.MinValue)
            {
                FirstOrder.Text = string.Format("{0:d}", firstOrderDate);
            }


            PurchaseTotalSummary paidSummary = ReportDataSource.CalculatePurchaseHistoryTotals(paidItems);

            GrossProduct.Text = paidSummary.GrossProductsTotal.LSCurrencyFormat("lc");
            Discount.Text     = String.Format("{0}", (paidSummary.DiscountsTotal * -1).LSCurrencyFormat("lc"));
            Coupon.Text       = String.Format("{0}", (paidSummary.CouponsTotal * -1).LSCurrencyFormat("lc"));
            NetProduct.Text   = paidSummary.NetProductTotal.LSCurrencyFormat("lc");

            ProfitLabel.Visible = paidSummary.CostOfGoodsSoldTotal > 0;
            Profit.Visible      = paidSummary.CostOfGoodsSoldTotal > 0;

            Profit.Text          = paidSummary.ProfitTotal.LSCurrencyFormat("lc");
            Taxes.Text           = paidSummary.TaxesTotal.LSCurrencyFormat("lc");
            Shipping.Text        = paidSummary.ShippingTotal.LSCurrencyFormat("lc");
            Other.Text           = paidSummary.OtherTotal.LSCurrencyFormat("lc");
            TotalPayments.Text   = paidSummary.TotalCharges.LSCurrencyFormat("lc");
            PurchasesToDate.Text = paidSummary.TotalCharges.LSCurrencyFormat("lc");

            PaidOrders.Text = paidSummary.OrderIds.Count.ToString();
            if (paidSummary.OrderIds.Count == 0)
            {
                PaidOrdersPanel.Visible = false;
            }


            PurchaseTotalSummary unpaidSummary = ReportDataSource.CalculatePurchaseHistoryTotals(unpaidItems);

            UnpaidGrossProduct.Text = unpaidSummary.GrossProductsTotal.LSCurrencyFormat("lc");
            UnpaidDiscount.Text     = String.Format("{0}", (unpaidSummary.DiscountsTotal * -1).LSCurrencyFormat("lc"));
            UnpaidCoupon.Text       = String.Format("{0}", (unpaidSummary.CouponsTotal * -1).LSCurrencyFormat("lc"));
            UnpaidNetProduct.Text   = unpaidSummary.NetProductTotal.LSCurrencyFormat("lc");

            UnpaidProfitLabel.Visible = unpaidSummary.CostOfGoodsSoldTotal > 0;
            UnpaidProfit.Visible      = unpaidSummary.CostOfGoodsSoldTotal > 0;

            UnpaidProfit.Text          = unpaidSummary.ProfitTotal.LSCurrencyFormat("lc");
            UnpaidTaxes.Text           = unpaidSummary.TaxesTotal.LSCurrencyFormat("lc");
            UnpaidShipping.Text        = unpaidSummary.ShippingTotal.LSCurrencyFormat("lc");
            UnpaidOther.Text           = unpaidSummary.OtherTotal.LSCurrencyFormat("lc");
            UnpaidTotalPayments.Text   = unpaidSummary.UnpaidTotal.LSCurrencyFormat("lc");
            UnpaidPurchasedToDate.Text = unpaidSummary.TotalCharges.LSCurrencyFormat("lc");

            PendingOrders.Text = unpaidSummary.OrderIds.Count.ToString();
            if (unpaidSummary.OrderIds.Count == 0)
            {
                UnpaidOrdersPanel.Visible = false;
            }
        }
        /// <summary>
        /// Saves this Wishlist object to the database.
        /// </summary>
        /// <returns><b>SaveResult</b> enumeration that represents the result of the save operation.</returns>
        protected SaveResult BaseSave()
        {
            if (this.IsDirty)
            {
                Database database     = Token.Instance.Database;
                bool     recordExists = true;

                if (this.WishlistId == 0)
                {
                    recordExists = false;
                }

                if (recordExists)
                {
                    //verify whether record is already present
                    StringBuilder selectQuery = new StringBuilder();
                    selectQuery.Append("SELECT COUNT(*) As RecordCount FROM ac_Wishlists");
                    selectQuery.Append(" WHERE WishlistId = @WishlistId");
                    using (DbCommand selectCommand = database.GetSqlStringCommand(selectQuery.ToString()))
                    {
                        database.AddInParameter(selectCommand, "@WishlistId", System.Data.DbType.Int32, this.WishlistId);
                        if ((int)database.ExecuteScalar(selectCommand) == 0)
                        {
                            recordExists = false;
                        }
                    }
                }

                int result = 0;
                if (recordExists)
                {
                    //UPDATE
                    StringBuilder updateQuery = new StringBuilder();
                    updateQuery.Append("UPDATE ac_Wishlists SET ");
                    updateQuery.Append("UserId = @UserId");
                    updateQuery.Append(", Name = @Name");
                    updateQuery.Append(", ViewPassword = @ViewPassword");
                    updateQuery.Append(" WHERE WishlistId = @WishlistId");
                    using (DbCommand updateCommand = database.GetSqlStringCommand(updateQuery.ToString()))
                    {
                        database.AddInParameter(updateCommand, "@WishlistId", System.Data.DbType.Int32, this.WishlistId);
                        database.AddInParameter(updateCommand, "@UserId", System.Data.DbType.Int32, this.UserId);
                        database.AddInParameter(updateCommand, "@Name", System.Data.DbType.String, NullableData.DbNullify(this.Name));
                        database.AddInParameter(updateCommand, "@ViewPassword", System.Data.DbType.String, NullableData.DbNullify(this.ViewPassword));
                        //RESULT IS NUMBER OF RECORDS AFFECTED
                        result = database.ExecuteNonQuery(updateCommand);
                    }
                }
                else
                {
                    //INSERT
                    StringBuilder insertQuery = new StringBuilder();
                    insertQuery.Append("INSERT INTO ac_Wishlists (UserId, Name, ViewPassword)");
                    insertQuery.Append(" VALUES (@UserId, @Name, @ViewPassword)");
                    insertQuery.Append("; SELECT Scope_Identity()");
                    using (DbCommand insertCommand = database.GetSqlStringCommand(insertQuery.ToString()))
                    {
                        database.AddInParameter(insertCommand, "@WishlistId", System.Data.DbType.Int32, this.WishlistId);
                        database.AddInParameter(insertCommand, "@UserId", System.Data.DbType.Int32, this.UserId);
                        database.AddInParameter(insertCommand, "@Name", System.Data.DbType.String, NullableData.DbNullify(this.Name));
                        database.AddInParameter(insertCommand, "@ViewPassword", System.Data.DbType.String, NullableData.DbNullify(this.ViewPassword));
                        //RESULT IS NEW IDENTITY;
                        result           = AlwaysConvert.ToInt(database.ExecuteScalar(insertCommand));
                        this._WishlistId = result;
                    }
                }
                this.SaveChildren();

                //OBJECT IS DIRTY IF NO RECORDS WERE UPDATED OR INSERTED
                this.IsDirty = (result == 0);
                if (this.IsDirty)
                {
                    return(SaveResult.Failed);
                }
                else
                {
                    return(recordExists ? SaveResult.RecordUpdated : SaveResult.RecordInserted);
                }
            }

            //SAVE IS SUCCESSFUL IF OBJECT IS NOT DIRTY
            return(SaveResult.NotDirty);
        }