Esempio n. 1
0
 /// <summary>
 /// Copies the item Properties to items.
 /// </summary>
 /// <param name="itemPropertyIds">The item property ids.</param>
 /// <param name="targetItemNumbers">The target item numbers.</param>
 /// <returns></returns>
 public static Dictionary<string, object> CopyItemPropertiesToItems( List<object> itemPropertyIds, List<object> targetItemNumbers )
 {
     Dictionary<string, object> j = new Dictionary<string, object>();
     foreach( object _itemPropertyId in itemPropertyIds ) {
         string itemPropertyId = ( string )_itemPropertyId;
         foreach( object _itemNumber in targetItemNumbers ) {
             string itemNumber = ( string )_itemNumber;
             string sqlCommand = @"insert into itemProperties select
             newId() as itemPropertyId, @itemNumber as itemNumber, itemProperty, propertyValue, displayValue,
             valueOrder, BOMItem, price, taxable, showAsSeperateLineOnInvoice, showInFilter,
             null as VerCol from itemProperties with (nolock) where itemPropertyId = @itemPropertyId";
             using(SqlConnection cn = Site.CreateConnection(true, true)) {
                 cn.Open();
                 using(SqlCommand cmd = new SqlCommand(sqlCommand, cn)) {
                     cmd.Parameters.Add("@itemPropertyId", SqlDbType.UniqueIdentifier).Value = new Guid(itemPropertyId);
                     cmd.Parameters.Add("@itemNumber", SqlDbType.VarChar).Value = itemNumber;
                     cmd.ExecuteNonQuery();
                 }
             }
         }
     }
     j.Add( "error", 0 );
     j.Add( "description", "" );
     return j;
 }
Esempio n. 2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SiteSection"/> class.
 /// </summary>
 /// <param name="_id">The _id.</param>
 /// <param name="_name">The _name.</param>
 /// <param name="_description">The _description.</param>
 /// <param name="_URL">The _ URL.</param>
 public SiteSection( Guid _id, string _name, string _description, string _URL )
 {
     Entries = new List<SiteSectionEntry>();
     Id = _id;
     Description = _description;
     Url = _URL;
     Name = _name;
 }
Esempio n. 3
0
 /// <summary>
 /// Copies the specified file path sources.
 /// </summary>
 /// <param name="filePathSources">The file path sources.</param>
 /// <param name="filePathDest">The file path dest.</param>
 /// <param name="move">if set to <c>true</c> [move].</param>
 /// <returns></returns>
 public static Dictionary<string, object> Cp( List<object> filePathSources, string filePathDest, bool move )
 {
     ( "FUNCTION /w (!PRIVATE ACCESS ONLY!),fileSystem cp" ).Debug( 10 );
     Dictionary<string, object> j = new Dictionary<string, object>();
     string secPath = Main.PhysicalApplicationPath.Substring( 0, Main.PhysicalApplicationPath.Length - 1 );
     string path = "";
     string exSecMsg = "Access outside of physical site path not allowed";
     string strFtp = "ftp://";
     string strVSiteRoot = "~";
     string backSlash = "\\";
     try {
         using(Impersonation imp = new Impersonation()) {
             string dest = filePathDest.Replace("~", Main.PhysicalApplicationPath);
             foreach(string file in filePathSources as List<object>) {
                 if((!filePathDest.Contains(strFtp)) && (!file.Contains(strFtp))) {
                     /* if LOCAL to LOCAL */
                     string f = file.ToString().Replace(strVSiteRoot, Main.PhysicalApplicationPath);
                     /* both source and dest must be in the site */
                     if(Main.FileSystemAccess == FileSystemAccess.Site && ((!f.Contains(secPath) || !dest.Contains(secPath)))) {
                         Exception e = new Exception(exSecMsg);
                         throw e;
                     }
                     if(f.EndsWith(backSlash)) {
                         path = Path.GetDirectoryName(Path.GetDirectoryName(f));
                         string fName = Path.GetFileName(Path.GetDirectoryName(f));
                         string fDest = Path.Combine(dest, fName);
                         if(!move) {
                             if(!Directory.Exists(fDest)) {
                                 Directory.CreateDirectory(fDest);
                             }
                         }
                         RecursiveCopy(f, fDest, move);
                     } else {
                         path = Path.GetDirectoryName(f);
                         if(move) {
                             File.Move(f, Path.Combine(dest, Path.GetFileName(f)));
                         } else {
                             File.Copy(f, Path.Combine(dest, Path.GetFileName(f)));
                         }
                     }
                 }
             }
         }
     } catch( Exception e ) {
         j.Add( "error", -1 );
         j.Add( "source", e.Source );
         j.Add( "description", e.Message );
     }
     if( path.Length > 0 ) {
         Dictionary<string, object> l = Ls( path );
         return l;
     } else {
         return j;
     }
 }
Esempio n. 4
0
 /// <summary>
 /// Posts the journal entries.
 /// This method might work but it has never been
 /// tested and is not impmented in Rendition 1.0
 /// </summary>
 /// <param name="journalEntries">The journal entries.
 /// Must be a JSON object in this format:
 ///		{
 /// 		userId: int userId,
 /// 		debit: float debit,
 /// 		credit: float credit,
 /// 		date: string date (MM/DD/YYYY),
 /// 		comments: string comments
 /// 	}
 /// </param>
 /// <returns>{error:0,desc:"error description"}</returns>
 public static Dictionary<string, object> PostJournalEntries(List<object> journalEntries)
 {
     Dictionary<string, object> j = new Dictionary<string, object>();
     SqlConnection cn = Site.CreateConnection(true, true);
     cn.Open();
     SqlTransaction trans = cn.BeginTransaction("postJournalEntries");
     bool commitTrans = true;
     string desc = "";
     string commandText = @"insert into generalLedger
     (generalLedgerId,refId,refType,creditRecord,debitRecord,
     amount,userId,addDate,reference,generalLedgerInsertId) values
     (
         newId(),
         convert(varchar(50),newId()),
         10/*manual*/,
         case when @debit > 0 then convert(bit,0) else convert(bit,1) end,
         case when @credit > 0 then convert(bit,0) else convert(bit,1) end,
         case when @debit > 0 then @debit else @credit end,
         @userId,
         @date,
         @reference,
         newId()
     )";
     int error = 0;
     try {
         foreach(Dictionary<string, object> entry in journalEntries) {
             using(SqlCommand cmd = cn.CreateCommand()) {
                 cmd.CommandText = commandText;
                 cmd.CommandType = CommandType.Text;
                 cmd.Transaction = trans;
                 cmd.Parameters.Add("@userId", SqlDbType.Int).Value = Convert.ToInt32(entry["userId"]);
                 cmd.Parameters.Add("@debit", SqlDbType.Money).Value = Convert.ToDecimal(entry["debit"]);
                 cmd.Parameters.Add("@credit", SqlDbType.Money).Value = Convert.ToDecimal(entry["credit"]);
                 cmd.Parameters.Add("@date", SqlDbType.DateTime).Value = Convert.ToDateTime(entry["date"]);
                 cmd.Parameters.Add("@reference", SqlDbType.VarChar).Value = entry["comments"];
                 cmd.ExecuteNonQuery();
             }
         }
     } catch(Exception ex) {
         error = -1;
         desc = ex.Message;
         commitTrans = false;
     }
     if(commitTrans) {
         trans.Commit();
         j.Add("error", 0);
         j.Add("description", "");
         return j;
     } else {
         trans.Rollback("postJournalEntries");
         j.Add("error", error);
         j.Add("description", desc);
         return j;
     }
 }
Esempio n. 5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Category"/> class.
 /// </summary>
 /// <param name="categoryName">Name of the category.</param>
 /// <param name="categoryId">The category id.</param>
 /// <param name="enabled">When true the category is enabled.</param>
 public Category( string categoryName, Guid categoryId, bool enabled )
 {
     Items = new List<Item>();
     this.Id = categoryId;
     this.Name = categoryName.Trim();
     this.Enabled = enabled;
     URLMatch = new Regex(String.Format(Main.CategoryRewrite,
         Name,
         Id, Name.Replace(" ", "-"),
         Name.Replace(" ", "_"),
         Name.Replace(" ", ".")));
 }
Esempio n. 6
0
 /// <summary>
 /// Gets the child orders by order id.
 /// </summary>
 /// <param name="orderId">The order id.</param>
 /// <param name="cn">SQL connection.</param>
 /// <param name="trans">The trans.</param>
 /// <returns>
 /// A list of orders matching the serial ids.
 /// </returns>
 public static List<Order> GetChildOrdersByOrderId(int orderId, SqlConnection cn, SqlTransaction trans)
 {
     using(SqlCommand cmd = new SqlCommand("select orderId from orders with (nolock) where parentOrderId = @orderId", cn, trans)) {
         cmd.Parameters.Add("@orderId", SqlDbType.Int).Value = orderId;
         using(SqlDataReader d = cmd.ExecuteReader()) {
             List<int> orderIds = new List<int>();
             while(d.Read()) {
                 orderIds.Add(d.GetInt32(0));
             }
             return GetOrdersByOrderIds(orderIds.ToArray(), cn, trans);
         }
     }
 }
Esempio n. 7
0
 /// <summary>
 /// Imports one or more categories.
 /// </summary>
 /// <param name="preview">if set to <c>true</c> [preview].</param>
 /// <param name="dupeMode">if set to <c>true</c> [dupe mode].</param>
 /// <param name="categories">The categories.</param>
 /// <returns></returns>
 public static List<object> ImportCategories( bool preview, bool dupeMode, List<object> categories )
 {
     Dictionary<string, object> j = new Dictionary<string, object>();
     List<object> outputCategoryList = new List<object>();
     using(SqlConnection cn = Site.CreateConnection(true, true)) {
         cn.Open();
         using( SqlTransaction trns = cn.BeginTransaction( "Import categories" ) ) {
             foreach( Dictionary<string, object> k in categories ) {
                 outputCategoryList.Add( ImportCategory( ( Dictionary<string, object> )k, dupeMode, cn, trns ) );
             }
             if( preview ) {
                 trns.Rollback();
             } else {
                 trns.Commit();
             }
         }
     }
     return outputCategoryList;
 }
Esempio n. 8
0
 /// <summary>
 /// Executes the scripted event.
 /// </summary>
 /// <param name="eventType">Type of the event.</param>
 /// <param name="taskId">The task id.</param>
 /// <param name="name">The name.</param>
 /// <param name="sourceCode">The source code.</param>
 /// <param name="language">The language.</param>
 /// <param name="sender">The sender.</param>
 /// <param name="scriptArguments">The <see cref="System.EventArgs"/> instance containing the event data.</param>
 /// <param name="preview">if set to <c>true</c> [preview].</param>
 /// <returns></returns>
 public static Dictionary<string, object> ExecuteScriptedEvent(string eventType, Guid taskId, string name, string sourceCode, string language, object sender, EventArgs scriptArguments, bool preview)
 {
     ("EVENT " + eventType + " > delegate " + name + "(" + taskId.ToString() + ")").Debug(10);
     Dictionary<string, object> j = new Dictionary<string, object>();
     string consoleOutput = "";
     string errorNumber = "";
     string errorJSON = "";
     DateTime startDate = DateTime.Now;
     List<object> errors = new List<object>();
     object[] args = { sender, scriptArguments };
     object obj = Admin.ExecuteScript(sourceCode, language, "script", "main", ref args, ref errors);
     if(errors.Count == 0) {
         if(consoleOutput.Length > 0) {
             if(obj.GetType() == typeof(string)) {
                 consoleOutput = (string)obj;
             }
             Dictionary<string, object> err = new Dictionary<string, object>();
             err.Add("errorNumber", 0);
             err.Add("errorText", "EVENT " + eventType + " > delegate " + name + " completed without error.");
             (" --------------------------------------------------").Debug(6);
             (" |		MESSAGE FROM " + name).Debug(6);
             (" --------------------------------------------------").Debug(6);
             (consoleOutput).Debug(6);/*MESSAGE!*/
             (" --------------------------------------------------").Debug(6);
             err.Add("line", 0);
             errorNumber = "0";
             errorJSON = err.ToJson();
             err["errorText"].Debug(6);
         }
     } else {
         errorJSON = errors.ToJson();
         errorNumber = (string)((Dictionary<string, object>)(errors[0]))["errorNumber"].ToString();
         errorJSON.Debug(6);
     }
     if(!preview) {
         updateEventTaskStatus(taskId, startDate, false, DateTime.Now, errorNumber, errorJSON);
     }
     j.Add("error", errorNumber);
     j.Add("errors", errors);
     j.Add("console", consoleOutput);
     return j;
 }
Esempio n. 9
0
 /// <summary>
 /// Executes the image template.  This is a reciprecol function.
 /// </summary>
 /// <param name="image">The image.</param>
 /// <param name="imageTemplateId">The image template id.</param>
 /// <param name="errors">The errors.</param>
 /// <returns></returns>
 public static System.Drawing.Bitmap ExecuteImageTemplate( System.Drawing.Bitmap image, string imageTemplateId, ref List<object> errors )
 {
     ( "FUNCTION /w SP,ADHOC executeImageTemplate" ).Debug( 10 );
     string commandText = @"select imagingTemplateDetailId, imagingTemplateId, name,
         description, script, language,filterOrder, enabled, template
         from imagingTemplateDetail
         where imagingTemplateId = @imagingTemplateId or imagingTemplateDetailId = @imagingTemplateId";
     using(Impersonation imp = new Impersonation()) {
         using(SqlConnection cn = Site.CreateConnection(true, true)) {
             cn.Open();
             using(SqlCommand cmd = new SqlCommand(commandText, cn)) {
                 cmd.Parameters.Add("@imagingTemplateId", SqlDbType.UniqueIdentifier).Value = new Guid(imageTemplateId.ToString());
                 using(SqlDataReader d = cmd.ExecuteReader()) {
                     if(d.HasRows) {
                         while(d.Read()) {
                             if(d.GetGuid(8) != Guid.Empty) {
                                 ExecuteImageTemplate(image, d.GetGuid(8).ToString(), ref errors);
                             } else {
                                 object[] args = { image };
                                 object obj = ExecuteScript(d.GetString(4), d.GetString(5), "script", "main", ref args, ref errors);
                                 if(errors.Count == 0) {
                                     if(obj.GetType() == typeof(System.Drawing.Bitmap)) {
                                         image = (System.Drawing.Bitmap)obj;
                                     } else {
                                         ("Error in template: " + d.GetGuid(1).ToString() +
                                         " Imaging script must return type System.Drawing.Bitmap.").Debug(1);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return image;
 }
Esempio n. 10
0
 /// <summary>
 /// Sets main defaults.
 /// </summary>
 void InitSetMainDefaults(HttpApplication _app)
 {
     /* initialize all static fields and properties */
     if(App == null) {
         App = _app;
         UseFormsBasedAuth = true;
         PhysicalApplicationPath = AppDomain.CurrentDomain.BaseDirectory;
         Compression = DEFAULT_COMPRESSION;
         MethodKey = DEFAULT_METHOD_KEY;
         CategoryRewrite = DEFAULT_CATEGORYREWRITE;
         PublicFiles = default_public_files;
         CategoryRewriteReplace = DEFAULT_CATEGORYREWRITEREPLACE;
         ItemRewrite = DEFAULT_ITEMREWRITE;
         ItemRewriteReplace = DEFAULT_ITEMREWRITEREPLACE;
         PublicDirectory = DEFAULT_PUBLICDIRECTORY;
         AdminDirectory = DEFAULT_ADMINDIRECTORY;
         PluginDirectory = DEFAULT_PLUGINDIRECTORY;
         UserDirectory = DEFAULT_USERDIRECTORY;
         ImageDirectory = DEFAULT_IMAGEDIRECTORY;
         TempDirectory = DEFAULT_TEMPDIRECTORY;
         RequestCategory = DEFAULT_REQUESTCATEGORY;
         RequestItem = DEFAULT_REQUESTITEM;
         Responder = DEFAULT_RESPONDER;
         AdminResponder = DEFAULT_ADMINRESPONDER;
         MainJSScript = DEFAULT_MAINJSCRIPT;
         ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
         Rendition.Main.UIScripts = new List<string>();
         Items = new Dictionary<string, object>();
         MainScripts = new List<string>();
         Conversations = new List<Admin.Conversation>();
         SystemMessages = new List<Dictionary<string, object>>();
         Timers = new List<Admin.Timer>();
         Plugins = new List<Plugin>();
         RevokedPlugins = new List<string[]>();
     }
 }
Esempio n. 11
0
 /// <summary>
 /// Applies the imaging template.
 /// </summary>
 /// <param name="templateId">The template id.</param>
 /// <param name="img">The img.</param>
 /// <returns></returns>
 public static System.Drawing.Bitmap ApplyImageTemplate( string templateId, System.Drawing.Bitmap img )
 {
     ( "FUNCTION /w SP,binaryStream applyImageTemplate" ).Debug( 10 );
     using(Impersonation imp = new Impersonation()) {
         using(SqlConnection cn = Site.CreateConnection(true, true)) {
             cn.Open();
             using(SqlCommand cmd = new SqlCommand("select imagingTemplateDetailID,template from imagingTemplateDetail where enabled = 1 and imagingTemplateId = @imagingTemplateId order by filterOrder asc", cn)) {
                 cmd.Parameters.Add("@imagingTemplateId", SqlDbType.UniqueIdentifier).Value = new Guid(templateId.ToString());
                 using(SqlDataReader r = cmd.ExecuteReader()) {
                     if(r.HasRows) {
                         while(r.Read()) {
                             if(r.GetGuid(1) != Guid.Empty) {
                                 img = ApplyImageTemplate(r.GetGuid(1).ToString(), img);
                             } else {
                                 List<object> errors = new List<object>();
                                 img = ExecuteImageTemplate(img, r.GetGuid(0).ToString(), ref errors);
                                 if(errors.Count > 0) {
                                     foreach(Dictionary<string, object> d in errors) {
                                         String.Format(" --------------------------------------------------\n" +
                                         " Error:" + d["errorNumber"] + "\n" +
                                         " Description:" + d["errorText"] + "\n" +
                                         " Line:" + d["line"] + "\n" +
                                         " --------------------------------------------------").Debug(1);
                                     }
                                 }
                             }
                         }
                     }
                 }
                 return img;
             }
         }
     }
 }
Esempio n. 12
0
 /// <summary>
 /// Cancels the items.
 /// </summary>
 /// <param name="args">The args.</param>
 /// <returns>{error:0,desc:""}</returns>
 public static Dictionary<string, object> CancelItems(List<object> args)
 {
     ("FUNCTION /w SP cancelItems").Debug(10);
     return CancelBackorderItems(args, true);
 }
Esempio n. 13
0
            /// <summary>
            /// Recalculates the order.
            /// </summary>
            /// <param name="args">The order arguments.</param>
            /// <param name="fcn">The FCN.</param>
            /// <param name="ftrans">The ftrans.</param>
            /// <returns>{error:0,desc:""}</returns>
            public static Dictionary<string, object> RecalculateOrder(Dictionary<string, object> args, SqlConnection fcn, SqlTransaction ftrans)
            {
                Dictionary<string, object> vt;
                Dictionary<string, object> j;
                Commerce.CreditCard card = null;
                Commerce.Cash cash = null;
                Commerce.Wire wire = null;
                // never used -> Commerce.PayPal PayPal=null;
                Commerce.Check check = null;
                Commerce.PromiseToPay promiseToPay = null;
                decimal discountAmount = 0;
                Guid paymentMethodId = Guid.NewGuid();
                bool backorder = false;
                bool preview = false;
                int errorId = -1;
                ("FUNCTION /w SP,CN,TRANS recalculateOrder").Debug(10);
                string[] keys = { "userId", "orderSessionId", "cartSessionId", "preview", "purchaseOrder" };
                bool transactionSucsessStatus = false;
                int termId = 0;
                int orderId = 0;
                decimal difference = 0;
                foreach(string keyName in keys) {
                    if(!args.ContainsKey(keyName)) {
                        Dictionary<string, object> o = new Dictionary<string, object>();
                        string _msg = "The key \"" + keyName + "\" is missing from the argument dictionary.  All keys must be present even if they are blank.";
                        o.Add("error", -4010);
                        o.Add("description", _msg);
                        String.Format("recalculateOrder failed. {0}", _msg).Debug(1);
                        return o;
                    }
                }
                /* get the old order */
                SqlConnection cn;
                SqlTransaction trans;
                Guid orderSessionId = new Guid((string)args["orderSessionId"]);
                if(fcn == null) {
                    cn = Site.CreateConnection(true, true);
                    cn.Open();
                    trans = cn.BeginTransaction("Recalculate transaction");
                } else {
                    cn = fcn;
                    trans = ftrans;
                }
                Commerce.Order originalOrder = Commerce.Order.GetOrderBySessionId(orderSessionId, cn, trans);
                termId = originalOrder.TermId;
                preview = Convert.ToBoolean(args["preview"].ToString());
                if(!preview) {
                    /* preview the recalculation in preview to asertain the grand total for charging the card */
                    trans.Save("preChargePreview");
                    j = ExecPlaceOrder(
                        orderSessionId,
                        Convert.ToInt32(args["userId"].ToString()),
                        orderSessionId,
                        true,/*preview*/
                        new Guid(Main.Site.Defaults.SiteId),
                        new Guid((string)args["cartSessionId"]),
                        args["purchaseOrder"].ToString(),
                        DateTime.Now/* this value is ignored in the SP for recalculations */,
                        termId,
                        discountAmount,
                        cn,
                        trans
                    );
                    termId = (int)j["termId"];
                    orderId = (int)j["orderId"];
                    if(j["error"].ToString() != "0" && j["error"].ToString() != "5") {
                        Exception ex = new Exception(j["description"].ToString());
                        throw ex;
                    }
                    if(!decimal.TryParse(j["difference"].ToString(), out difference)) {
                        difference = 0;
                    }
                    difference = Math.Round(difference, 2, MidpointRounding.AwayFromZero);
                    if(difference != 0) {
                        if(backorder) {
                            /* no need to do anything */
                        } else if(termId == 0 && difference > 0) {/*this is a prepaid credit card transaction - termId 0 */
                            /* don't try and charge credit cards negitive amounts */
                            card = new Commerce.CreditCard(
                                args["cardType"].ToString().MaxLength(50, true),
                                args["cardNumber"].ToString().MaxLength(100, true),
                                args["nameOnCard"].ToString().MaxLength(100, true),
                                args["secNumber"].ToString().MaxLength(7, true),
                                args["expMonth"].ToString().MaxLength(4, true),
                                args["expYear"].ToString().MaxLength(4, true)
                            );
                            List<int> orderIds = new List<int>();
                            orderIds.Add(orderId);
                            card.Insert(paymentMethodId, orderSessionId, originalOrder.UserId, originalOrder.SessionId,
                            termId, "", difference, DateTime.Now, orderIds, "", cn, trans);
                        } else if(termId == 9 /* this is a COD Check transaction - termId 9 */ ) {
                            check = new Commerce.Check(
                                args["checkNumber"].ToString().MaxLength(50, true),
                                args["routingNumber"].ToString().MaxLength(50, true),
                                args["bankAccountNumber"].ToString().MaxLength(50, true),
                                args["checkNotes"].ToString().MaxLength(50, true)
                            );
                            List<int> orderIds = new List<int>();
                            orderIds.Add(orderId);
                            check.Insert(paymentMethodId, originalOrder.UserId, originalOrder.SessionId, termId, "", difference, DateTime.Now, orderIds, "", cn, trans);
                        } else if(termId == 20 /* this is a wire transfer - termId 20 */ ) {
                            wire = new Commerce.Wire(
                                args["swift"].ToString().MaxLength(50, true),
                                args["bankName"].ToString().MaxLength(50, true),
                                args["routingTransitNumber"].ToString().MaxLength(50, true)
                            );
                            List<int> orderIds = new List<int>();
                            orderIds.Add(orderId);
                            wire.Insert(paymentMethodId, originalOrder.UserId, originalOrder.SessionId, termId, "", difference, DateTime.Now, orderIds, "", cn, trans);
                        } else if(termId == 13 /* this order is prepaid in cash */) {
                            cash = new Commerce.Cash(); /*don't you wish it was really that easy?*/
                            List<int> orderIds = new List<int>();
                            orderIds.Add(orderId);
                            cash.Insert(paymentMethodId, originalOrder.UserId, originalOrder.SessionId, termId, "", difference, DateTime.Now, orderIds, "", cn, trans);
                        } else if(difference > 0) {
                            /* this order is an accrued order */
                            promiseToPay = new Commerce.PromiseToPay();
                            List<int> orderIds = new List<int>();
                            orderIds.Add(orderId);
                            promiseToPay.Insert(paymentMethodId, originalOrder.UserId, originalOrder.SessionId, termId, "", difference, DateTime.Now, orderIds, "", cn, trans);
                        }
                    }
                    trans.Rollback("preChargePreview");
                }
                /* do the recalculation */
                j = ExecPlaceOrder(
                    new Guid((string)args["orderSessionId"]),
                    Convert.ToInt32(args["userId"].ToString()),
                    new Guid((string)args["orderSessionId"]),
                    preview,
                    new Guid(Main.Site.Defaults.SiteId),
                    new Guid((string)args["cartSessionId"]),
                    args["purchaseOrder"].ToString(),
                    DateTime.Now/* this value is ignored in the SP for recalculations */,
                    termId,
                    discountAmount,
                    cn,
                    trans
                );
                errorId = Convert.ToInt32(j["error"].ToString());
                if(errorId != 0 && errorId != 5) {/* if there was an return the error without continuing */
                    if(fcn == null) {
                        trans.Rollback();
                        cn.Close();
                    }
                    return j;
                };

                if(termId != 0 || backorder == true) {
                    /* this order uses acrued payment method or has lost value, don't charge now */
                    ("order with payment terms, backorder.  No payment gateway now.").Debug(7);
                    transactionSucsessStatus = true;
                } else if(difference > 0) {
                    ("starting payment gateway...").Debug(5);
                    vt = Commerce.VirtualTerminal.ChargeCreditCard(
                        (Commerce.Address)j["billToAddress"], (Commerce.Address)j["shipToAddress"], card,
                        difference, new Guid((string)args["orderSessionId"]), originalOrder.OrderNumber,
                        originalOrder.PurchaseOrder, fcn, ftrans
                    );
                    if(vt == null) {
                        Dictionary<string, object> o = new Dictionary<string, object>();
                        trans.Rollback();
                        o.Add("error", -1754);
                        o.Add("description", "Internal virtual terminal error.  Unable to create virtual terminal object.");
                        ("Invalid credit card passed to local system").Debug(7);
                        ("placeOrder Failed with error code -1754").Debug(7);
                        if(fcn == null) {
                            cn.Dispose();
                        }
                        return o;
                    }
                    transactionSucsessStatus = vt["error"].ToString() == "0";
                    if(!transactionSucsessStatus) {
                        j.Add("error", -3);
                        j.Add("description", vt["description"]);
                        j.Add("virtualTerminal", vt);
                        if(fcn == null) {
                            cn.Dispose();
                        }
                        return j;
                    }
                }
                if(errorId != 0 || transactionSucsessStatus == false || preview) {
                    if(fcn == null) {
                        trans.Rollback();
                    }
                    if(!preview) {
                        Exception ex = new Exception("The trasnaction failed.");
                        throw ex;
                    }
                } else {
                    Commerce.Order order;
                    RecalculateOrderEventArgs e;
                    if(fcn == null) {
                        order = Commerce.Order.GetOrderByOrderId(orderId, cn, trans);
                        e = new RecalculateOrderEventArgs(order, cn, trans, args, Main.GetCurrentSession(), HttpContext.Current);
                    } else {
                        order = Commerce.Order.GetOrderByOrderId(orderId, fcn, ftrans);
                        e = new RecalculateOrderEventArgs(order, fcn, ftrans, args, Main.GetCurrentSession(), HttpContext.Current);
                    }
                    Main.Site.raiseOnrecalculateorder(e);
                    if(Site.AbortDefaultEvent == true) {
                        Site.AbortDefaultEvent = false;
                    }
                    if(fcn == null) {
                        trans.Commit();
                    }
                }
                if(fcn == null) {
                    cn.Dispose();
                }
                return j;
            }
Esempio n. 14
0
 /// <summary>
 /// Renders the template images.  Updates an ProgressInfo matching progressInfoId parameter.
 /// </summary>
 /// <param name="templateId">The template id.</param>
 /// <param name="progressInfoId">The progress info id.</param>
 /// <returns></returns>
 public static List<object> RenderTemplateImages( string templateId, string progressInfoId )
 {
     Guid id = new Guid( progressInfoId );
     ProgressInfo u = new ProgressInfo( id );
     if( !Main.ProgressInfos.ContainsKey( id ) ) {
         Main.ProgressInfos.Add( id, u );
     } else {
         Main.ProgressInfos[ id ] = u;
     }
     u.CurrentItemName = "Starting";
     u.TotalItemCount = 0;
     u.Started = DateTime.Now;
     ( "FUNCTION /w SP renderTemplateImages" ).Debug( 10 );
     List<object> l = new List<object>();
     List<object> entries = new List<object>();
     using(Impersonation imp = new Impersonation()) {
         using(SqlConnection cn = Site.CreateConnection(true, true)) {
             cn.Open();
             using(SqlCommand cmd = new SqlCommand("getTemplateUsage @templateId", cn)) {
                 cmd.Parameters.Add("@templateId", SqlDbType.UniqueIdentifier).Value = new Guid(templateId.ToString());
                 using(SqlDataReader d = cmd.ExecuteReader()) {
                     if(d.HasRows) {
                         while(d.Read()) {
                             foreach(Commerce.Item i in Main.Site.Items.List) {
                                 u.TotalItemCount++;
                                 string[] ls = { d.GetString(1) };
                                 List<object> f = new List<object>();
                                 f.Add(i.ItemNumber);
                                 f.Add(ls);
                                 f.Add(d.GetGuid(0));
                                 entries.Add(f);
                             }
                         }
                     }
                 }
             }
         }
         foreach(List<object> entry in entries) {
             l.Add(RefreshItemImages(((string)entry[0]), ((string[])entry[1]), ((Guid)(entry[2])), Guid.Empty));
             u.CurrentItemCount++;
             u.Updated = DateTime.Now;
             u.CurrentItemName = ((string)entry[0]);
         }
     }
     u.Complete = true;
     return l;
 }
Esempio n. 15
0
 /// <summary>
 /// Updates the cart based on the dictionary provided.
 /// Pass the quantity of the item as qty+jguid(cartId) or as the jguid(cartId)
 /// All other form variables should be passed using their cartDetailId.
 /// </summary>
 /// <param name="args">The args.</param>
 /// <returns>{error:0,desc:"error description",items:item Collection,subTotal:x,taxTotal:x,estShipTotal:x,discountTotal:x,grandTotal:x,addresses:addressCollection}.</returns>
 public static Dictionary<string, object> UpdateCart(Dictionary<string, object> args)
 {
     ("FUNCTION /w SP updateCart").Debug(10);
     Dictionary<string, object> j = new Dictionary<string, object>();
     Session session = null;
     if(args.ContainsKey("sessionId")) {
         session = new Session(Main.Site, new Guid((string)args["sessionId"]));
     } else {
         session = Main.GetCurrentSession();
     }
     if(session.Cart.Items.Count == 0) {
         session.Cart.Refresh();
     }
     foreach(Commerce.CartItem i in session.Cart.Items) {
         /* check for each QTY key, if the key exists then update this item. */
         if(args.ContainsKey(i.CartId.EncodeXMLId())) {
             string formId = i.CartId.EncodeXMLId();
             int qty = 0;/* if a qty was passed, and it turns out not to be numeric, then you loose the item */
             if(!int.TryParse(args[formId].ToString(), out qty)) {
                 qty = 0;
             }
             Guid addressId = Guid.Empty;
             if(args.ContainsKey("addressId")) {
                 addressId = new Guid(args["addressId"].ToString());
             }
             SqlCommand cmd = new SqlCommand(Cart.UPDATE_CART_QUERY, Site.SqlConnection);
             cmd.Parameters.Add("@qty", SqlDbType.Int).Value = args[i.CartId.EncodeXMLId()];
             cmd.Parameters.Add("@price", SqlDbType.Money).Value = 0;
             cmd.Parameters.Add("@cartId", SqlDbType.UniqueIdentifier).Value = new Guid(i.CartId.ToString());
             cmd.Parameters.Add("@setPrice", SqlDbType.Bit).Value = false;
             cmd.Parameters.Add("@addressId", SqlDbType.UniqueIdentifier).Value = addressId;
             cmd.ExecuteNonQuery();
             cmd.Dispose();
             UpdateCartDetail(i, args);
         }
     }
     session.Cart.Refresh();
     List<object> items = new List<object>();
     foreach(Commerce.CartItem i in session.Cart.Items) {
         Dictionary<string, object> jt = new Dictionary<string, object>();
         jt.Add("cartId", i.CartId);
         jt.Add("price", i.Price);
         jt.Add("qty", i.Qty);
         jt.Add("addressId", i.AddressId);
         jt.Add("inputs", i.Inputs);
         items.Add(jt);
     }
     j.Add("items", items);
     j.Add("subTotal", (float)session.Cart.SubTotal);
     j.Add("taxTotal", (float)session.Cart.TaxTotal);
     j.Add("estShipTotal", (float)session.Cart.EstShipTotal);
     j.Add("discountTotal", (float)session.Cart.DiscountTotal);
     j.Add("grandTotal", (float)session.Cart.GrandTotal);
     j.Add("addresses", session.Cart.Addresses);
     j.Add("error", 0);
     j.Add("description", "");
     return j;
 }
Esempio n. 16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ZipToZones"/> class.
 /// </summary>
 /// <param name="site">The site.</param>
 public ZipToZones(Site site)
 {
     List = new List<ZipToZone>();
     using(SqlConnection cn = Site.CreateConnection(true, true)) {
         cn.Open();
         using(SqlCommand cmd = new SqlCommand("dbo.getZipToZones", cn)) {
             using(SqlDataReader zoneList = cmd.ExecuteReader()) {
                 while(zoneList.Read()) {
                     List.Add(new ZipToZone(
                         zoneList.GetGuid(0),
                         zoneList.GetInt32(1),
                         zoneList.GetInt32(2),
                         zoneList.GetInt32(3),
                         zoneList.GetInt32(4),
                         zoneList.GetInt32(5),
                         zoneList.GetInt32(6)
                     ));
                 }
             }
         }
     }
 }
Esempio n. 17
0
 /// <summary>
 /// Cancels or backorders the items in an existing order.
 /// </summary>
 /// <param name="args">The args.</param>
 /// <param name="cancel">if set to <c>true</c> [cancel] else backorder</param>
 /// <returns>{error:0,desc:""}</returns>
 private static Dictionary<string, object> CancelBackorderItems(List<object> args, bool cancel)
 {
     /*TODO: backorder procedure has uncertain payment stuff going on here
      * cancel works, backorder works, but changing
      *
      */
     Dictionary<string, object> j = new Dictionary<string, object>();
     using(SqlConnection cn = Site.CreateConnection(true, true)) {
         cn.Open();
         using(SqlTransaction cancelBackorderTransaction = cn.BeginTransaction("Backorder or Cancel")) {
             bool rollback = true;
             try {
                 foreach(object line in args) {
                     Dictionary<string, object> fields = (Dictionary<string, object>)line;
                     // never used -->Dictionary<string,object> flag;
                     if(!fields.ContainsKey("serialId") || !fields.ContainsKey("qty")) {
                         Exception e = new Exception("key serialId or qty is missing");
                         throw e;
                     }
                     int serialId = Convert.ToInt32(fields["serialId"].ToString());
                     int qty = Convert.ToInt32(fields["qty"].ToString());
                     /* update the cart table with the number of items to be backordered.   */
                     using(SqlCommand cmd = new SqlCommand("update cart set returnToStock = @return where serialId = @serialId", cn, cancelBackorderTransaction)) {
                         cmd.Parameters.Add("@serialId", SqlDbType.Int).Value = serialId;
                         cmd.Parameters.Add("@return", SqlDbType.Int).Value = qty;
                         cmd.ExecuteNonQuery();
                     }
                     /* now add the flag that will trigger serial_line.TR_LINE_DEPLETE_INVENTORY*/
                     /* flag -11 is backorder, flag -12 is cancel */
                     using(SqlCommand cmd = new SqlCommand("dbo.backorderCancel @serialId,@cancel,@backorder", cn, cancelBackorderTransaction)) {
                         cmd.Parameters.Add("@serialId", SqlDbType.Int).Value = serialId;
                         cmd.Parameters.Add("@cancel", SqlDbType.Bit).Value = cancel;
                         cmd.Parameters.Add("@backorder", SqlDbType.Bit).Value = !cancel;
                         cmd.ExecuteNonQuery();
                     }
                     /* if this is a cancelation don't create a new order or add to an existing order */
                     if(cancel) {
                         AddFlagWithTransaction("0", "line", serialId.ToString(), "Quantity of " + qty + " canceled", cn, cancelBackorderTransaction);
                     } else {
                         /* first check to see if an order is already the child of this order
                             * if so, then just add this item to the child order (backorder)
                             * if there is no child order than create the child order now.
                             */
                         Commerce.Order childOrder;
                         List<Commerce.Order> childOrders = Commerce.Order.GetChildOrdersBySerialId(serialId, cn, cancelBackorderTransaction);
                         if(childOrders.Count == 0) {
                             childOrder = null;
                         } else {
                             childOrder = childOrders[0];
                         }
                         Commerce.Order order = Commerce.Order.GetOrderBySerialId(serialId, cn, cancelBackorderTransaction);
                         if(childOrder == null) {
                             /* create a new order and add the item's qty to the new order */
                             /* get the line that will be added to the backorder */
                             List<Commerce.Line> sourceLines = order.Lines.FindAll(delegate(Commerce.Line ln) {
                                 return ln.SerialId == serialId && ln.KitAllocationCartId == ln.CartId;
                             });
                             /* sort the items by int kitAllocationId */
                             sourceLines.Sort(delegate(Commerce.Line l1, Commerce.Line l2) {
                                 return l1.KitAllocationId.CompareTo(l2.KitAllocationId);
                             });
                             /* when there is more than one source line, always pick the one with the larget id
                                 * this will be the parent/virtual item that needs to be added to the backorder */
                             Commerce.Line sourceLine = sourceLines[sourceLines.Count - 1];
                             /* create a new session for the new order */
                             Session session = new Session(Main.Site, cn, cancelBackorderTransaction);
                             Site.LogOn(order.UserId, session, cn, cancelBackorderTransaction);
                             session.Refresh(false, cn, cancelBackorderTransaction);
                             AddToCartArguments addTocartArgs = new AddToCartArguments();
                             addTocartArgs["itemNumber"] = sourceLine.ItemNumber;
                             addTocartArgs["qty"] = fields["qty"].ToString();
                             addTocartArgs["customerLineNumber"] = sourceLine.CustomLineNumber;
                             addTocartArgs["sessionId"] = session.Id.ToString();
                             addTocartArgs["price"] = sourceLine.Price;
                             addTocartArgs["allowPreorder"] = true;
                             /* add all of the inputs as arguments */
                             Dictionary<string, object> addToCartArgs = Cart.AddToCart(addTocartArgs, cn, cancelBackorderTransaction);
                             if(Convert.ToInt32(addToCartArgs["error"]) != 0) {
                                 Exception e = new Exception(addToCartArgs["description"].ToString());
                                 throw e;
                             }
                             Guid newCartId = new Guid(addToCartArgs["cartId"].ToString());
                             /* copy all of the order header data into the new order */
                             using(SqlCommand cmd = new SqlCommand("dbo.duplicateCartDetail @sourceCartId,@targetCartId", cn, cancelBackorderTransaction)) {
                                 cmd.Parameters.Add("@sourceCartId", SqlDbType.UniqueIdentifier).Value = new Guid(sourceLine.CartId.ToString());
                                 cmd.Parameters.Add("@targetCartId", SqlDbType.UniqueIdentifier).Value = new Guid(newCartId.ToString());
                                 cmd.ExecuteNonQuery();
                             }
                             OrderArguments newOrderArgs = new OrderArguments();
                             newOrderArgs["billToFirstName"] = order.BillToAddress.FirstName;
                             newOrderArgs["billToLastName"] = order.BillToAddress.LastName;
                             newOrderArgs["billToAddress1"] = order.BillToAddress.Address1;
                             newOrderArgs["billToAddress2"] = order.BillToAddress.Address2;
                             newOrderArgs["billToCity"] = order.BillToAddress.City;
                             newOrderArgs["billToState"] = order.BillToAddress.State;
                             newOrderArgs["billToZip"] = order.BillToAddress.Zip;
                             newOrderArgs["billToCountry"] = order.BillToAddress.Country;
                             newOrderArgs["billToHomePhone"] = order.BillToAddress.HomePhone;
                             newOrderArgs["billToWorkPhone"] = order.BillToAddress.WorkPhone;
                             newOrderArgs["billToCompany"] = order.BillToAddress.Company;
                             newOrderArgs["billToComments"] = order.BillToAddress.Comments;
                             newOrderArgs["billToSpecialInstructions"] = order.BillToAddress.SpecialInstructions;
                             newOrderArgs["billToSendShipmentUpdates"] = order.BillToAddress.SendShipmentUpdates;
                             newOrderArgs["FOB"] = order.FOB;
                             newOrderArgs["termId"] = order.TermId;
                             newOrderArgs["userId"] = session.User.UserId;
                             newOrderArgs["manifestNumber"] = order.Manifest;
                             newOrderArgs["purchaseOrder"] = Utilities.Iif(order.PurchaseOrder.Length > 0, order.PurchaseOrder + ">" + order.OrderNumber, "");
                             newOrderArgs["sessionId"] = session.Id.ToString();
                             newOrderArgs["shipToRateId"] = -1;/* never put a shipping method on backorders */
                             newOrderArgs["billToRateId"] = -1;
                             newOrderArgs["shipToEmailAds"] = false;
                             newOrderArgs["billToEmailAds"] = false;
                             newOrderArgs["billToSendShipmentUpdates"] = false;
                             newOrderArgs["shipToFirstName"] = order.ShipToAddress.FirstName;
                             newOrderArgs["shipToLastName"] = order.ShipToAddress.LastName;
                             newOrderArgs["shipToAddress1"] = order.ShipToAddress.Address1;
                             newOrderArgs["shipToAddress2"] = order.ShipToAddress.Address2;
                             newOrderArgs["shipToCity"] = order.ShipToAddress.City;
                             newOrderArgs["shipToState"] = order.ShipToAddress.State;
                             newOrderArgs["shipToZip"] = order.ShipToAddress.Zip;
                             newOrderArgs["shipToCountry"] = order.ShipToAddress.Country;
                             newOrderArgs["shipToHomePhone"] = order.ShipToAddress.HomePhone;
                             newOrderArgs["shipToWorkPhone"] = order.ShipToAddress.WorkPhone;
                             newOrderArgs["shipToCompany"] = order.ShipToAddress.Company;
                             newOrderArgs["shipToComments"] = order.ShipToAddress.Comments;
                             newOrderArgs["shipToSpecialInstructions"] = order.ShipToAddress.SpecialInstructions;
                             newOrderArgs["shipToSendShipmentUpdates"] = order.ShipToAddress.SendShipmentUpdates;
                             newOrderArgs["parentOrderId"] = order.OrderId;
                             newOrderArgs["comments"] = "This order is a backorder from Order " + order.OrderNumber;
                             newOrderArgs.Add("backorder", true);
                             /* place the new backorder */
                             Dictionary<string, object> newOrder = Commerce.Order.PlaceOrderWithTransaction(newOrderArgs, cn, cancelBackorderTransaction);
                             if(Convert.ToInt32(newOrder["error"]) != 0) {
                                 Exception e = new Exception(newOrder["description"].ToString());
                                 throw e;
                             }
                             childOrder = Commerce.Order.GetOrderByOrderNumber((string)newOrder["orderNumber"], cn, cancelBackorderTransaction);
                             j.Add("childOrder", childOrder.GetOrderJson());
                         } else {
                             /* the child order (backorder) already existed, so add the item to the backorder */
                             Commerce.Line sourceLine = order.Lines.Find(delegate(Commerce.Line ln) {
                                 return ln.SerialId == serialId;
                             });
                             /* create a new session for the new order */
                             Session session = new Session(Main.Site, cn, cancelBackorderTransaction);
                             Site.LogOn(childOrder.UserId, session, cn, cancelBackorderTransaction);
                             session.Refresh(false, cn, cancelBackorderTransaction);
                             AddToCartArguments addTocartArgs = new AddToCartArguments();
                             addTocartArgs["itemNumber"] = sourceLine.ItemNumber;
                             addTocartArgs["qty"] = fields["qty"].ToString();
                             addTocartArgs["customerLineNumber"] = sourceLine.CustomLineNumber;
                             addTocartArgs["sessionId"] = session.Id.ToString();
                             addTocartArgs["addressId"] = sourceLine.AddressId.ToString();
                             addTocartArgs["price"] = sourceLine.Price;
                             addTocartArgs["allowPreorder"] = true;
                             /* add all of the inputs as arguments */
                             Dictionary<string, object> addToCartArgs = Cart.AddToCart(addTocartArgs, cn, cancelBackorderTransaction);
                             if(Convert.ToInt32(addToCartArgs["error"]) != 0) {
                                 Exception e = new Exception(addToCartArgs["description"].ToString());
                                 throw e;
                             }
                             Guid newCartId = new Guid(addToCartArgs["cartId"].ToString());
                             /* copy all of the order header data into the new order */
                             using(SqlCommand cmd = new SqlCommand("dbo.duplicateCartDetail @sourceCartId,@targetCartId", cn, cancelBackorderTransaction)) {
                                 cmd.Parameters.Add("@sourceCartId", SqlDbType.UniqueIdentifier).Value = new Guid(sourceLine.CartId.ToString());
                                 cmd.Parameters.Add("@targetCartId", SqlDbType.UniqueIdentifier).Value = new Guid(newCartId.ToString());
                                 cmd.ExecuteNonQuery();
                             }
                             Dictionary<string, object> recalculateArgs = new Dictionary<string, object>();
                             recalculateArgs.Add("userId", childOrder.UserId);
                             recalculateArgs.Add("orderSessionId", childOrder.SessionId.ToString());
                             recalculateArgs.Add("cartSessionId", session.Id.ToString());
                             recalculateArgs.Add("cardType", "");
                             recalculateArgs.Add("cardNumber", "");
                             recalculateArgs.Add("expMonth", "");
                             recalculateArgs.Add("expYear", "");
                             recalculateArgs.Add("secNumber", "");
                             recalculateArgs.Add("nameOnCard", "");
                             recalculateArgs.Add("billToAddressId", childOrder.BillToAddress.Id.ToString());
                             recalculateArgs.Add("shipToAddressId", childOrder.ShipToAddress.Id.ToString());
                             recalculateArgs.Add("preview", false);
                             recalculateArgs.Add("purchaseOrder", childOrder.PurchaseOrder);
                             recalculateArgs.Add("backorder", true);
                             Dictionary<string, object> recalculatedOrder = RecalculateOrder(recalculateArgs, cn, cancelBackorderTransaction);
                             if((int)recalculatedOrder["error"] != 0) {
                                 Exception e = new Exception(recalculatedOrder["description"].ToString());
                                 throw e;
                             }
                             Commerce.Order _order = Commerce.Order.GetOrderByOrderNumber((string)recalculatedOrder["orderNumber"], cn, cancelBackorderTransaction);
                             j.Add("childOrder", _order.GetOrderJson());
                         }
                         AddFlagWithTransaction("0", "line", serialId.ToString(), "Quantity of " + qty + " added to backorder " + childOrder.OrderNumber, cn, cancelBackorderTransaction);
                     }
                 }
                 rollback = false;
                 cancelBackorderTransaction.Commit();
                 j.Add("error", 0);
                 j.Add("description", "");
             } catch(Exception e) {
                 rollback = true;
                 j.Add("error", -1);
                 j.Add("description", e.Message);
             } finally {
                 if(rollback) {
                     cancelBackorderTransaction.Rollback();
                 }
             }
         }
     }
     return j;
 }
Esempio n. 18
0
 /// <summary>
 /// deletes the specified file paths.
 /// </summary>
 /// <param name="filePaths">The file paths.</param>
 /// <returns></returns>
 public static Dictionary<string, object> Rm( List<object> filePaths )
 {
     ( "FUNCTION /w (!PRIVATE ACCESS ONLY!),fileSystem rm" ).Debug( 10 );
     Dictionary<string, object> j = new Dictionary<string, object>();
     string path = "";
     bool isDirectory = false;
     string showPathWhenDone = "";
     try {
         using(Impersonation imp = new Impersonation()) {
             foreach(string file in filePaths as List<object>) {
                 isDirectory = Directory.Exists(file);
                 path = Path.GetDirectoryName(file.Replace("~", Main.PhysicalApplicationPath));
                 if(!isDirectory) {
                     showPathWhenDone = path;
                 } else {
                     DirectoryInfo di = new DirectoryInfo(path);
                     showPathWhenDone = di.Parent.FullName;
                 }
                 if(Main.FileSystemAccess == FileSystemAccess.Site && (!path.Contains(Main.PhysicalApplicationPath.Substring(0, Main.PhysicalApplicationPath.Length - 1)))) {
                     Exception e = new Exception("Access outside of physical site path not allowed");
                     throw e;
                 }
                 /* is this a file or directory ? */
                 if(isDirectory) {
                     /* delete this directory tree */
                     Directory.Delete(file, true);
                 } else {
                     /* delete this file */
                     File.Delete(file);
                 }
             }
         }
     } catch( Exception e ) {
         j.Add( "error", -1 );
         j.Add( "source", e.Source );
         j.Add( "description", e.Message );
         return j;
     }
     if( path.Length > 0 ) {
         Dictionary<string, object> l = Ls(showPathWhenDone);
         return l;
     }
     j.Add( "error", -2 );
     j.Add( "source", "unknown" );
     j.Add( "description", "an unknown error has occured" );
     return j;
 }
Esempio n. 19
0
 /// <summary>
 /// Gets the plugins from the plugin directory.
 /// </summary>
 internal static void getPlugins()
 {
     ( "looking for plugins..." ).Debug( 10 );
     // scan the plugins and bin directories if any for DLLs to hookup
     string pluginDirName = Main.PluginDirectory.Replace("~/", PhysicalApplicationPath);
     string binDirName = PhysicalApplicationPath + "bin";
     List<string> files = new List<string>(Directory.GetFiles(binDirName));
     if(Directory.Exists(pluginDirName)) {
         files.AddRange(Directory.GetFiles(pluginDirName));
     }
     foreach( string file in files ) {
         // load dll files only
         if( Path.GetExtension( file ).ToLower() == ".dll" &&
             (!file.EndsWith("Rendition.Core.dll")) ) {
             try {
                 // open a stream for reading so the file doesn't get locked
                 byte[] asmBytes = System.IO.File.ReadAllBytes(file);
                 Assembly asm = Assembly.Load(asmBytes);
                 AddPlugin(asm);
             } catch( ReflectionTypeLoadException e ) {
                 String.Format( "Plugin {0} threw an exception on Activator.CreateInstance.{1}",
                 file, e.LoaderExceptions ).Debug( 1 );
             }
         }
     }
 }
Esempio n. 20
0
 /// <summary>
 /// List the specified path.
 /// </summary>
 /// <param name="path">The path.</param>
 /// <returns></returns>
 public static Dictionary<string, object> Ls( string path )
 {
     ( "FUNCTION /w (!PRIVATE ACCESS ONLY!),fileSystem ls" ).Debug( 10 );
     Dictionary<string, object> j = new Dictionary<string, object>();
     ArrayList dirs = new ArrayList();
     ArrayList files = new ArrayList();
     List<object> f = new List<object>();
     Dictionary<string, object> up = new Dictionary<string, object>();
     try {
         using(Impersonation imp = new Impersonation()) {
             if(path.Length == 0) {
                 string targetDirectory = Main.PhysicalApplicationPath;
                 if(Main.GetCurrentSession().UserId == -1) {
                     targetDirectory += "user\\public";
                     if(!Directory.Exists(targetDirectory)) {
                         Directory.CreateDirectory(targetDirectory);
                     }
                 } else {
                     targetDirectory += "user\\" + Convert.ToString(Main.GetCurrentSession().UserId);
                     if(!Directory.Exists(targetDirectory)) {
                         Directory.CreateDirectory(targetDirectory);
                     }
                 }
                 /*
                  * this seems like it woulbe be cool, but really it isn't
                  * so lets just put this here
                  * */
                 path = Main.PhysicalApplicationPath;
             }
             if(path.StartsWith("/")) {
                 path = path.TrimStart('/');
             }
             /* trim ending slash */
             if(path.EndsWith("\\")) {
                 path = path.Substring(0, path.Length - 1);
             }
             if(!path.Contains(":")) {
                 path = Main.PhysicalApplicationPath + path.Replace("/", "\\");
             }
             if(Main.FileSystemAccess == FileSystemAccess.Site && (!path.Contains(Main.PhysicalApplicationPath.Substring(0, Main.PhysicalApplicationPath.Length - 1)))) {
                 Exception e = new Exception("Access outside of physical site path not allowed");
                 throw e;
             }
             files.AddRange(Directory.GetFiles(path));
             dirs.AddRange(Directory.GetDirectories(path));
             if(path.Length > 3) {
                 up.Add("name", path + "\\..");
                 up.Add("size", 0);
                 up.Add("creationTime", "");
                 up.Add("lastAccessTime", "");
                 up.Add("lastWriteTime", "");
                 up.Add("objectType", "directory");
                 f.Add(up);
             }
             foreach(string dir in dirs) {
                 Dictionary<string, object> fd = new Dictionary<string, object>();
                 fd.Add("name", dir);
                 fd.Add("size", 0);
                 fd.Add("creationTime", File.GetCreationTime(dir));
                 fd.Add("lastAccessTime", File.GetLastAccessTime(dir));
                 fd.Add("lastWriteTime", File.GetLastWriteTime(dir));
                 fd.Add("objectType", "directory");
                 f.Add(fd);
             }
             foreach(string file in files) {
                 /* for some reason some files are listed that are not actually there
                  * for instance C:\WebDev.WebServer20.EXE shows in the list
                  * but is not in the directory.  */
                 try {
                     Dictionary<string, object> fd = new Dictionary<string, object>();
                     fd.Add("name", file);
                     FileInfo info = new FileInfo(file);
                     fd.Add("size", info.Length);
                     fd.Add("creationTime", info.CreationTime);
                     fd.Add("lastAccessTime", info.LastAccessTime);
                     fd.Add("lastWriteTime", info.LastWriteTime);
                     fd.Add("objectType", info.Extension);
                     f.Add(fd);
                 } catch{ }
             }
             j.Add("files", f);
             j.Add("error", 0);
             j.Add("description", "");
         }
     } catch( Exception e ) {
         j.Add( "error", -1 );
         j.Add( "source", e.Source );
         j.Add( "description", e.Message );
     }
     return j;
 }
Esempio n. 21
0
 /// <summary>
 /// Gets the logical drives.
 /// </summary>
 /// <returns></returns>
 public static List<object> GetLogicalDrives()
 {
     ( "FUNCTION /w (!PRIVATE ACCESS ONLY!),fileSystem getLogicalDrives" ).Debug( 10 );
     List<object> j = new List<object>();
     string[] drives = Directory.GetLogicalDrives();
     foreach( string drive in drives ) {
         Dictionary<string, object> fd = new Dictionary<string, object>();
         fd.Add( "name", drive );
         j.Add( fd );
     }
     return j;
 }
Esempio n. 22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Cart"/> class.
 /// </summary>
 /// <param name="f_session">The f_session.</param>
 /// <param name="f_site">The f_site.</param>
 public Cart( Session f_session, Site f_site )
 {
     EstShippingCost = 0;
     EstShipTotal = 0;
     SubTotal = 0;
     GrandTotal = 0;
     TaxTotal = 0;
     DiscountTotal = 0;
     Items = new List<CartItem>();
     Addresses = new List<Address>();
     Session = f_session;
     Site = f_site;
 }
Esempio n. 23
0
 /// <summary>
 /// Gets the item images for use in a backend application.
 /// </summary>
 /// <param name="itemNumber">The item number.</param>
 /// <returns></returns>
 public static List<object> GetItemImages( string itemNumber )
 {
     List<object> l = new List<object>();
     using( SqlConnection cn = Site.CreateConnection(true, true) ){
         cn.Open();
         using(SqlCommand cmd = new SqlCommand(@"select imagingId, fileSize, fileName, thumbnail,
         thumbOrder, height, width from imaging with (nolock) where itemnumber = @itemnumber;", cn)) {
             cmd.Parameters.Add("@itemnumber", SqlDbType.VarChar).Value = itemNumber;
             using(SqlDataReader r = cmd.ExecuteReader()) {
                 while(r.Read()) {
                     Dictionary<string, object> j = new Dictionary<string, object>();
                     Guid imgId = r.GetGuid(0);
                     string fileName = r.GetString(2);
                     j.Add("imagingId", imgId.ToString());
                     j.Add("fileSize", r.GetInt32(1).ToString());
                     j.Add("fileName", fileName);
                     j.Add("thumbnail", r.GetBoolean(3));
                     j.Add("thumbOrder", r.GetInt32(4));
                     j.Add("height", r.GetInt32(5));
                     j.Add("width", r.GetInt32(6));
                     j.Add("src", imgId.ToFileName() + Path.GetExtension(fileName));
                     l.Add(j);
                 }
             }
         }
     }
     return l;
 }
Esempio n. 24
0
 /// <summary>
 /// Gets most of the order's by info using various methods. Formated for JSON.
 /// </summary>
 /// <param name="orderNumber">The order number. Pass null if not used.</param>
 /// <param name="orderId">The order id. Pass a value less than 0 if not use.)</param>
 /// <param name="order">The order. If you already have an order object loaded you can pass it preventing addtional database queries.</param>
 /// <param name="cn">The sql connection.</param>
 /// <param name="trans">The transaction.</param>
 /// <returns></returns>
 public static Dictionary<string, object> GetOrderJson(string orderNumber, int orderId, Commerce.Order order,
     SqlConnection cn, SqlTransaction trans)
 {
     Dictionary<string, object> j = new Dictionary<string, object>();
     cn = (SqlConnection)Utilities.Iif(cn == null, Site.SqlConnection, cn);
     if(order == null) {
         if(orderNumber != null) {
             order = Commerce.Order.GetOrderByOrderNumber(orderNumber, cn, trans);
         } else if(orderId > -1) {
             order = Commerce.Order.GetOrderByOrderId(orderId, cn, trans);
         }
     }
     if(order == null) {
         j.Add("error", -1);
         j.Add("description", String.Format("Order {0} not found.", orderNumber));
         return j;
     }
     j.Add("error", 0);
     j.Add("description", "");
     j.Add("approvedBy", order.ApprovedBy);
     j.Add("billToAddress", order.BillToAddress);
     j.Add("canceled", order.Canceled);
     j.Add("closed", order.Closed);
     j.Add("comment", order.Comment);
     j.Add("deliverBy", order.DeliverBy);
     j.Add("discount", order.Discount);
     j.Add("FOB", order.FOB);
     j.Add("grandTotal", order.GrandTotal);
     j.Add("manifest", order.Manifest);
     j.Add("orderDate", order.OrderDate);
     j.Add("orderId", order.OrderId);
     j.Add("orderNumber", order.OrderNumber);
     j.Add("paid", order.Paid);
     j.Add("parentOrderId", order.ParentOrderId);
     j.Add("paymentMethodId", order.PaymentMethodId);
     j.Add("purchaseOrder", order.PurchaseOrder);
     j.Add("readyForExport", order.ReadyForExport);
     j.Add("recalculatedOn", order.RecalculatedOn);
     j.Add("requisitionedBy", order.RequisitionedBy);
     j.Add("scanned_order_image", order.ScannedOrderImage);
     j.Add("service1", order.Service1);
     j.Add("service2", order.Service2);
     j.Add("sessionId", order.SessionId);
     j.Add("shippingTotal", order.ShippingTotal);
     j.Add("shipToAddress", order.ShipToAddress);
     j.Add("soldBy", order.SoldBy);
     j.Add("subTotal", order.SubTotal);
     j.Add("taxTotal", order.TaxTotal);
     j.Add("term", order.Term);
     j.Add("user", order.User);
     j.Add("userId", order.UserId);
     j.Add("vendor_accountNo", order.VendorAccountNumber);
     j.Add("lastStatusId", order.LastStatusId);
     j.Add("lastStatus", order.LastStatus);
     List<Dictionary<string, object>> lines = new List<Dictionary<string, object>>();
     foreach(Commerce.Line line in order.Lines) {
         Dictionary<string, object> l = new Dictionary<string, object>();
         l.Add("addressId", line.AddressId);
         l.Add("addTime", line.AddTime);
         l.Add("backorderedQty", line.BackorderedQty);
         l.Add("canceledQty", line.CanceledQty);
         l.Add("cartId", line.CartId);
         l.Add("customLineNumber", line.CustomLineNumber);
         l.Add("epsmmcsAIFilename", line.EPSMMCSAIFileName);
         l.Add("epsmmcsOutput", line.EPSMMCSOutput);
         l.Add("estimatedFulfillmentDate", line.EstimatedFulfillmentDate);
         l.Add("fulfillmentDate", line.FulfillmentDate);
         l.Add("itemNumber", line.ItemNumber);
         l.Add("kitAllocationCartId", line.KitAllocationCartId);
         l.Add("kitAllocationId", line.KitAllocationId);
         l.Add("kitQty", line.KitQty);
         l.Add("lineDetail", line.LineDetail);
         l.Add("lineNumber", line.LineNumber);
         l.Add("noTaxValueCostTotal", line.NoTaxValueCostTotal);
         l.Add("orderId", line.OrderId);
         l.Add("orderNumber", line.OrderNumber);
         l.Add("parentCartId", line.ParentCartId);
         l.Add("price", line.Price);
         l.Add("qty", line.Qty);
         l.Add("serialId", line.SerialId);
         l.Add("serialNumber", line.SerialNumber);
         l.Add("shipmentId", line.ShipmentId);
         l.Add("shipmentNumber", line.ShipmentNumber);
         l.Add("showAsSeperateLineOnInvoice", line.ShowAsSeperateLineOnInvoice);
         l.Add("valueCostTotal", line.ValueCostTotal);
         l.Add("vendorItemKitAssignmentId", line.VendorItemKitAssignmentId);
         l.Add("lastStatus", line.LastStatus);
         l.Add("lastStatusId", line.LastStatusId);
         Dictionary<string, object> form = new Dictionary<string, object>();
         form.Add("HTML", line.Form.HtmlWithValues());
         form.Add("name", line.Form.Name);
         form.Add("inputs", line.Form.Inputs);
         form.Add("ext", line.Form.Extention);
         l.Add("form", form);
         l.Add("item", Admin.GetItem(line.ItemNumber));
         lines.Add(l);
     }
     j.Add("lines", lines);
     return j;
 }
Esempio n. 25
0
 /// <summary>
 /// Previews a single filter in a filter template.
 /// </summary>
 /// <param name="templateDetailId">The template detail id.</param>
 /// <param name="sampleImage">The sample image.</param>
 /// <param name="binaryOutput">if set to <c>true</c> [binary output].</param>
 /// <returns></returns>
 public static Dictionary<string, object> PreviewTemplateDetail( string templateDetailId, string sampleImage, bool binaryOutput )
 {
     ( "FUNCTION /w fileSystem previewTemplateDetail" ).Debug( 10 );
     Dictionary<string, object> j = new Dictionary<string, object>();
     // resrouce file in source path /js/admin/img/test_pattern.png
     byte[] buffer = getSampleImage();
     MemoryStream fms = new MemoryStream( buffer );
     System.Drawing.Bitmap img = ( System.Drawing.Bitmap )System.Drawing.Bitmap.FromStream( fms );
     List<object> errors = new List<object>();
     try {
         using(Impersonation imp = new Impersonation()) {
             img = ExecuteImageTemplate(img, templateDetailId, ref errors);
             if(errors.Count != 0) {
                 j.Add("error", -2);
                 j.Add("description", "One or more scripts generated errors.");
                 j.Add("errors", errors);
                 return j;
             }
         }
     } catch( Exception e ) {
         if( e.InnerException != null ) {
             j.Add( "description", "Internal server error: " + e.InnerException.Source + ": " + e.InnerException.Message );
         } else {
             j.Add( "description", "Internal server error: " + e.Source + ": " + e.Message );
         }
         return j;
     }
     Guid g = Guid.NewGuid();
     string tempFileName = "temp\\" + g.ToString() + ".jpg";
     if( !binaryOutput ) {
         using(Impersonation imp = new Impersonation()) {
             img.Save(Main.PhysicalApplicationPath + tempFileName);
         }
         Dictionary<string, object> ii = new Dictionary<string, object>();
         FileInfo f = new FileInfo( Main.PhysicalApplicationPath + tempFileName );
         ii.Add( "height", img.Height );
         ii.Add( "width", img.Width );
         ii.Add( "size", f.Length );
         j.Add( "imageInfo", ii );
         j.Add( "image", tempFileName.Replace( "\\", "/" ) );
         j.Add( "error", 0 );
         j.Add( "description", "" );
     } else {
         using( MemoryStream ms = new MemoryStream() ) {
             img.Save( ms, System.Drawing.Imaging.ImageFormat.Png );
             HttpContext.Current.Response.Clear();
             HttpContext.Current.Response.ContentType = "image/png";
             HttpContext.Current.Response.AddHeader( "Expires", "0" );/* RFC 2616 14.21 Content has already expired */
             HttpContext.Current.Response.AddHeader( "Cache-Control", "no-store" );/* RFC 2616 14.9.2 Don't ever cache */
             HttpContext.Current.Response.AddHeader( "Pragma", "no-store" );/* RFC 2616 14.32 Pragma - same as cache control */
             ms.WriteTo( HttpContext.Current.Response.OutputStream );
         }
         img.Dispose();
         HttpContext.Current.Response.Flush();
         HttpContext.Current.ApplicationInstance.CompleteRequest();
     }
     return j;
 }
Esempio n. 26
0
 /// <summary>
 /// Gets the orders by order ids.
 /// </summary>
 /// <param name="ids">The ids.</param>
 /// <param name="fcn">SQL connection.</param>
 /// <param name="ftrns">SQL transaction.</param>
 /// <returns>The matching orders.</returns>
 public static List<Order> GetOrdersByOrderIds(int[] ids, SqlConnection fcn, SqlTransaction ftrns)
 {
     List<Order> orders = new List<Order>();
     if(ids.Length == 0) { return orders; };
     List<SqlDataRecord> rowData = new List<SqlDataRecord>();
     SqlMetaData[] hashTable = {
         new SqlMetaData("keyName",SqlDbType.VarChar,100),
         new SqlMetaData("keyValue",SqlDbType.Variant),
         new SqlMetaData("primary_key",SqlDbType.Bit),
         new SqlMetaData("dataType",SqlDbType.VarChar,50),
         new SqlMetaData("dataLength",SqlDbType.Int),
         new SqlMetaData("varCharMaxValue",SqlDbType.VarChar,-1)
     };
     StringBuilder s = new StringBuilder();
     foreach(int id in ids) {
         SqlDataRecord rec = new SqlDataRecord(hashTable);
         rec.SetValue(0, "orderId");
         rec.SetValue(1, id);
         rec.SetBoolean(2, false);
         rec.SetString(3, "int");
         rec.SetValue(4, 8);
         rowData.Add(rec);
     }
     SqlConnection cn;
     if(fcn != null) {
         cn = fcn;
     } else {
         cn = Site.SqlConnection;
     }
     using(SqlCommand cmd = cn.CreateCommand()) {
         if(fcn != null) {
             cmd.Transaction = ftrns;
         }
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.CommandText = "dbo.getOrders";
         cmd.Parameters.Add("@orderIds", SqlDbType.Structured);
         cmd.Parameters["@orderIds"].Direction = ParameterDirection.Input;
         cmd.Parameters["@orderIds"].Value = rowData;
         using(SqlDataReader u = cmd.ExecuteReader()) {
             int orderId = -1;
             DateTime orderDate = DateTime.MinValue;
             decimal grandTotal = 0;
             decimal taxTotal = 0;
             decimal subTotal = 0;
             decimal shippingTotal = 0;
             decimal service1 = 0;
             decimal service2 = 0;
             string manifest = "";
             string purchaseOrder = "";
             decimal discount = 0;
             string comment = "";
             decimal paid = 0;
             Guid billToAddressId = Guid.Empty;
             bool closed = false;
             bool canceled = false;
             Guid paymentMethodId = Guid.Empty;
             int termId = -1;
             int userId = -1;
             string orderNumber = "";
             bool creditMemo = false;
             string scanned_order_image = "";
             DateTime readyForExport = DateTime.MinValue;
             DateTime recalculatedOn = DateTime.MinValue;
             Guid sessionId = Guid.Empty;
             int soldBy = -1;
             int requisitionedBy = -1;
             int approvedBy = -1;
             DateTime deliverBy = DateTime.MinValue;
             string vendor_accountNo = "";
             string FOB = "";
             int parentOrderId = -1;
             int order_status = -1;
             List<Line> lines = new List<Line>();
             while(u.Read()) {
                 /* #44 is orderId */
                 if(u.GetInt32(44) != orderId && orderId != -1) {
                     /*the orderId has changed, add the previous order */
                     orders.Add(new Order(
                         orderId, orderDate, grandTotal, taxTotal, subTotal, shippingTotal, service1,
                         service2, manifest, purchaseOrder, discount, comment, paid, billToAddressId, closed,
                         canceled, paymentMethodId, termId, userId, orderNumber, creditMemo, scanned_order_image,
                         readyForExport, recalculatedOn, sessionId, soldBy, requisitionedBy, approvedBy, deliverBy,
                         vendor_accountNo, FOB, parentOrderId, lines, order_status, cn, ftrns
                     ));
                     lines = new List<Line>();/* create a new list of lines for the next order */
                 }
                 orderId = u.GetInt32(44);
                 orderDate = u.GetDateTime(132);
                 grandTotal = u.GetDecimal(133);
                 taxTotal = u.GetDecimal(134);
                 subTotal = u.GetDecimal(135);
                 shippingTotal = u.GetDecimal(136);
                 service1 = u.GetDecimal(137);
                 service2 = u.GetDecimal(138);
                 manifest = u.GetString(139);
                 purchaseOrder = u.GetString(140);
                 discount = u.GetDecimal(164);
                 comment = u.GetString(141);
                 paid = u.GetDecimal(190);
                 billToAddressId = u.GetGuid(103);
                 closed = u.GetBoolean(191);
                 canceled = u.GetBoolean(191);
                 termId = u.GetInt32(84);
                 userId = u.GetInt32(55);
                 orderNumber = u.GetString(46);
                 creditMemo = u.GetBoolean(193);
                 scanned_order_image = u.GetString(53);
                 readyForExport = u.GetDateTime(7);
                 recalculatedOn = u.GetDateTime(194);
                 sessionId = u.GetGuid(38);
                 soldBy = u.GetInt32(195);
                 requisitionedBy = u.GetInt32(196);
                 approvedBy = u.GetInt32(197);
                 deliverBy = u.GetDateTime(198);
                 vendor_accountNo = u.GetString(199);
                 FOB = u.GetString(200);
                 parentOrderId = u.GetInt32(201);
                 order_status = u.GetInt32(5);
                 /* always add every line */
                 lines.Add(new Line(
                     u.GetGuid(37)/*cartId*/,
                     u.GetGuid(38)/*sessionId*/,
                     u.GetInt32(39)/*qty*/,
                     u.GetString(0)/*itemNumber*/,
                     u.GetDecimal(41)/*price*/,
                     u.GetDateTime(42)/*add time*/,
                     u.GetInt32(44)/*orderId*/,
                     u.GetInt32(45)/*serialId*/,
                     u.GetString(46)/*orderNumber*/,
                     u.GetString(47)/*serialNumber*/,
                     u.GetGuid(48)/*addressId*/,
                     u.GetInt32(49)/*shipmentId*/,
                     u.GetString(50)/*shipmentNumber*/,
                     u.GetInt32(51)/*lineNumber*/,
                     u.GetString(52)/*epsmmcsoutput*/,
                     u.GetString(54)/*epsmmcsfilename*/,
                     u.GetDecimal(170)/*valueCostTotal*/,
                     u.GetDecimal(171)/*noTaxValueCostTotal*/,
                     u.GetDateTime(203)/*fullfillmentDate*/,
                     u.GetDateTime(204)/*estimatedFulfillmentDate*/,
                     u.GetGuid(202)/*parentCartId*/,
                     u.GetInt32(12)/*backorderedqty*/,
                     u.GetInt32(13)/*canceledQty*/,
                     u.GetString(174)/*customLineNumber*/,
                     u.GetInt32(205)/*kitAllocationId*/,
                     u.GetInt32(206)/*kitQty*/,
                     u.GetBoolean(207)/*showAsSeperateLineOnInvoice*/,
                     u.GetGuid(208)/*vendorItemKitAssignmentId*/,
                     u.GetGuid(209)/*kitAllocationCartId*/,
                     u.GetInt32(1)/*line_status*/
                 ));
             }
             /* add the last order */
             orders.Add(new Order(
                 orderId, orderDate, grandTotal, taxTotal, subTotal, shippingTotal, service1,
                 service2, manifest, purchaseOrder, discount, comment, paid, billToAddressId, closed,
                 canceled, paymentMethodId, termId, userId, orderNumber, creditMemo, scanned_order_image,
                 readyForExport, recalculatedOn, sessionId, soldBy, requisitionedBy, approvedBy, deliverBy,
                 vendor_accountNo, FOB, parentOrderId, lines, order_status, cn, ftrns
             ));
             /* now all the shipments that belong to the orders */
             u.NextResult();
             while(u.Read()) {
                 int shipmentOrderId = u.GetInt32(0);
                 /* find the order that goes to this shipment */
                 Commerce.Order sOrd = orders.Find(delegate(Commerce.Order ord) {
                     return ord.OrderId == shipmentOrderId;
                 });
                 if(sOrd == null) { continue; }
                 /*
                 cart.orderId,addressUpdateId,cart.shipmentNumber,tracking,
                 dateShipped,actualWeight,actualService,actualCost,
                 actualBilledWeight,packageLength,packageWidth,
                 packageHeight,thirdPartyAccount,voidStatus,
                 emailSent,addDate
                 */
                 Shipment shp = new Shipment(sOrd.ShipToAddress, sOrd,
                 u.GetGuid(1), u.GetString(2), u.GetString(3),
                 u.GetString(4), u.GetString(5),
                 u.GetString(6), u.GetString(7),
                 u.GetString(8), u.GetString(9),
                 u.GetString(10), u.GetString(11),
                 u.GetString(12), u.GetString(13),
                 u.GetDateTime(14), u.GetDateTime(15));
                 sOrd.Shipments.Add(shp);
             }
             /* next batch... line detail
             cartDetailId, cartDetail.cartId,
             inputName, value, cartDetail.sessionId */
             u.NextResult();
             while(u.Read()) {
                 LineDetail lineDetail = new LineDetail(
                     u.GetGuid(0),
                     u.GetGuid(1),
                     u.GetGuid(4),
                     u.GetString(2),
                     u.GetString(3)
                 );
                 /* find the line to attach this line detail to */
                 Line line = lines.Find(delegate(Commerce.Line l) {
                     return l.CartId == lineDetail.CartId;
                 });
                 if(line != null) {
                     line.LineDetail.Add(lineDetail);
                 }
             }
             /* next batch... form source
             * order_line_forms.cartId, sourceCode, formName  */
             u.NextResult();
             while(u.Read()) {
                 Guid id = u.GetGuid(0);
                 Line line = lines.Find(delegate(Commerce.Line l) {
                     return l.CartId == id;
                 });
                 if(line != null) {
                     if(u.IsDBNull(1)) {
                         line.SourceCode = "";
                         line.FormName = "NO FORM";
                     } else {
                         line.SourceCode = u.GetString(1);
                         line.FormName = u.GetString(2);
                     }
                 }
             }
         }
     }
     return orders;
 }
Esempio n. 27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SiteImagePlaceholders"/> class.
 /// </summary>
 /// <param name="site">The site.</param>
 public SiteImagePlaceholders( Site site )
 {
     using(SqlConnection cn = Site.CreateConnection(true, true)) {
         cn.Open();
         using(SqlCommand cmd = new SqlCommand(@"select unique_siteId, m_imagingTemplate,c_imagingTemplate,f_imagingTemplate,t_imagingTemplate,
     a_imagingTemplate,x_imagingTemplate,y_imagingTemplate,z_imagingTemplate,b_imagingTemplate,d_imagingTemplate, siteaddress
     from site_configuration", cn)) {
             using(SqlDataReader r = cmd.ExecuteReader()) {
                 List = new List<SiteImagePlaceholder>();
                 while(r.Read()) {
                     List.Add(new SiteImagePlaceholder(
                         r.GetGuid(0),
                         r.GetGuid(1),
                         r.GetGuid(2),
                         r.GetGuid(3),
                         r.GetGuid(4),
                         r.GetGuid(5),
                         r.GetGuid(6),
                         r.GetGuid(7),
                         r.GetGuid(8),
                         r.GetGuid(9),
                         r.GetGuid(10),
                         r.GetString(11)
                     ));
                 }
             }
         }
     }
 }
Esempio n. 28
0
 /// <summary>
 /// Creates an item used to populate the class _cart.  This method does not add items to the database.
 /// </summary>
 /// <param name="_item_number">Item Number</param>
 /// <param name="_cartId">Cart Id from the table cart</param>
 /// <param name="_price">Price of the item in the cart</param>
 /// <param name="_qty">Quantity of this line item</param>
 /// <param name="_addressId">Address Id of the Address to ship to</param>
 /// <param name="addTime">The add time.</param>
 /// <param name="session">_session to attach this item to</param>
 public CartItem( string _item_number, Guid _cartId, decimal _price, int _qty, Guid _addressId, DateTime addTime, Session session )
 {
     if(Inputs == null) {
         Inputs = new List<Input>();
     }
     Item = Main.Site.Item( _item_number );
     CartId = _cartId;
     Price = _price;
     Qty = _qty;
     AddressId = _addressId;
     XMLId = _cartId.EncodeXMLId();
     XMLAddressId = _addressId.EncodeXMLId();
     AddedOn = addTime;
 }
Esempio n. 29
0
 /// <summary>
 /// Refreshes the user contacts.
 /// </summary>
 public void RefreshUserContacts()
 {
     _contacts = new List<Address>();
     string sqlCommand = @"select
     contactId,firstName,lastName,address1,address2,
     city,state,zip,country,homePhone,workPhone,email,specialInstructions,
     comments,sendshipmentupdates,emailads, rate,dateCreated,company
     from contacts with (nolock)	where userId = @userId";
     using(SqlConnection cn = Site.CreateConnection(true, true)) {
         cn.Open();
         using(SqlCommand cmd = new SqlCommand(sqlCommand, cn)) {
             cmd.Parameters.Add("@userId", SqlDbType.Int).Value = this.UserId;
             using(SqlDataReader d = cmd.ExecuteReader()) {
                 while(d.Read()) {
                     Address addr = new Address(
                     d.GetGuid(0),
                     d.GetString(1),
                     d.GetString(2),
                     d.GetString(3),
                     d.GetString(4),
                     d.GetString(5),
                     d.GetString(6),
                     d.GetString(7),
                     d.GetString(8),
                     d.GetString(9),
                     d.GetString(10),
                     d.GetString(11),
                     d.GetString(12),
                     d.GetString(13),
                     d.GetBoolean(14),
                     d.GetBoolean(15),
                     Main.Site.Rates.List.Find(delegate(Commerce.Rate t) {
                         return t.Id == d.GetInt32(16);
                     }),
                     d.GetDateTime(17),
                     d.GetString(18));
                     _contacts.Add(addr);
                 }
             }
         }
     }
 }
Esempio n. 30
0
        /// <summary>
        /// Exports the files.
        /// </summary>
        private void exportFiles()
        {
            /* create a connection and transaction in case this fails */
            string transactionName = "quickbooksExport";
            SqlConnection cn = Site.CreateConnection(true, true);
            cn.Open();
            SqlTransaction trans=cn.BeginTransaction(transactionName);
            this.Message="Checking for orders to import.";
            ("Quickbooks 10 Export: " + this.Message).Debug(10);
            /* generate file names */
            exportDate=DateTime.Now;
            string dateSuffix=exportDate.ToString("MM-dd-yyyy.hh-mm-ss");
            StringBuilder billFileBuffer=new StringBuilder(@"");
            StringBuilder invoiceFileBuffer=new StringBuilder(@"");
            StringBuilder billPaymentBuffer=new StringBuilder(@"");
            StringBuilder customerPaymentBuffer=new StringBuilder(@"");
            /* there are four potential output files */
            invoiceFileName="Invoice_"+dateSuffix+".iif";
            customer_paymentFileName="Customer_Payment_"+dateSuffix+".iif";
            billFileName="Bill_"+dateSuffix+".iif";
            bill_paymentFileName="Invoice_"+dateSuffix+".iif";
            ("Quickbooks 10 Export: " + this.Message).Debug(10);
            /* get the list of orders to export and close.  This represents bills and invoices. */
            List<int> orderIds=new List<int>();
            using(SqlCommand cmd=new SqlCommand(@"/* Quickbooks IIF Export. Check for orders to export */
            select orderId from orders o with (nolock)
            where not readyForExport = '1/1/1900 00:00:00.000' and not orderId in
            (
                select convert(int,cid) from
                (select controlId as cid from dbo.exportFileAudit a with (nolock) where controlIdType = '384D7FB0-164C-40FB-8FBB-B4CF0B77B1AF') cids
            )
            ", cn,trans)) {
                using(SqlDataReader r=cmd.ExecuteReader()) {
                    while(r.Read()) {
                        int orderId=r.GetInt32(0);
                        orderIds.Add(orderId);
                    }
                }
            }
            /* WARNING: THIS DOES NOT WORK - IT WILL NEVER WORK.  quickbooks does not support importing
             * payments to be associated with existing order because it's a f*****g steaming pile of useless shit
             *
             * get the list of payments and close.  This represents the bill and customer payment files */
            List<Guid> paymentIds=new List<Guid>();
            using(SqlCommand cmd=new SqlCommand(@"/* Quickbooks IIF Export. Check for payments to export */
            declare @emptyGuid uniqueidentifier = '00000000-0000-0000-0000-000000000000';
            declare @importPromiseToPay bit = 0;
            select paymentMethodId from paymentMethods with (nolock)
            where generalLedgerInsertId = @emptyGuid and (promiseToPay = 0 or promiseToPay = @importPromiseToPay) and paymentMethodId not in
            (
                select convert(uniqueidentifier,cid) from
                (select controlId as cid from dbo.exportFileAudit a with (nolock) where controlIdType = '3511CB96-333C-466D-AD3E-347DD75BD315') cids
            )
            ",cn,trans)) {
                cmd.Parameters.Add("@controlIdType",SqlDbType.UniqueIdentifier).Value=new Guid(orderControlId);
                using(SqlDataReader r=cmd.ExecuteReader()) {
                    if(r.HasRows) {
                        while(r.Read()) {
                            Guid paymentId=r.GetGuid(0);
                            paymentIds.Add(paymentId);
                        }
                    }
                }
            }
            /*
            * payments
            */
            this.Message="Creating Payment Files.";
            ("Quickbooks 10 Export: " + this.Message).Debug(10);
            foreach(Guid paymentId in paymentIds) {
                try {
                    Commerce.Payment payment = new Commerce.Payment(paymentId);
                    /* create the export string and validate it before adding it to the exportFileAudit table */
                    bool customer=payment.User.AccountType==0;
                    string fileName;
                    if(customer) {
                        fileName=bill_paymentFileName;
                    } else {
                        fileName=customer_paymentFileName;
                    }
            /* teamplates:
            *
            !TRNS	TRNSID	TRNSTYPE	DATE	ACCNT	NAME	AMOUNT	DOCNUM
            !SPL	SPLID	TRNSTYPE	DATE	ACCNT	NAME	AMOUNT	DOCNUM
            !ENDTRNS
            *
            *
            * CUSTOMER
            TRNS	 	PAYMENT	7/16/98	Undeposited Funds	Ecker Designs:Office Repairs	500	321
            SPL	 	PAYMENT	7/16/98	Accounts Receivable	Ecker Designs:Office Repairs	-500	321
            ENDTRNS

            * BILL
            *
            !TRNS	TRNSID	TRNSTYPE	DATE	ACCNT	NAME	AMOUNT	DOCNUM	MEMO	CLEAR	TOPRINT
            !SPL	SPLID	TRNSTYPE	DATE	ACCNT	NAME	AMOUNT	DOCNUM	MEMO	CLEAR	QNTY
            !ENDTRNS
            *
            *
            TRNS		BILLPMT	7/16/98	Checking	Bayshore CalOil Service	-35		Test Memo	N	Y
            SPL		BILLPMT	7/16/98	Accounts Payable	Bayshore CalOil Service	35			N
            ENDTRNS

            *
            */
                    if(customer) {
                        /* payments from customers */
                        string strPaymentDate = payment.GetAddress().DateCreated.ToString("MM/dd/yyyy");
                        customerPaymentBuffer.Append("TRNS	 	PAYMENT	"+strPaymentDate+
                        "	"+payment.User.UserId+"	"+payment.User.Handle+"	"+payment.Amount.ToString()+"	"+payment.Id.ToBase64Hash()+
                        Environment.NewLine);
                        foreach(Commerce.PaymentReference reference in payment.PaymentRefrences){
                            customerPaymentBuffer.Append("SPL	 	PAYMENT	"+strPaymentDate+
                            "	Accounts Receivable	Order Number:"+reference.Order.OrderNumber+"	"+
                            (reference.Amount*-1).ToString()+"	"+reference.Order.OrderNumber+
                            Environment.NewLine);
                        }
                        customerPaymentBuffer.Append("ENDTRNS"+Environment.NewLine);
                    } else {
                        /* payments to vendors */
                        string strPaymentDate = payment.GetAddress().DateCreated.ToString("MM/dd/yyyy");
                        billPaymentBuffer.Append("TRNS		BILLPMT	"+strPaymentDate+
                        "	Checking	"+payment.User.Handle+"	"+(payment.Amount*-1).ToString()+"		"+payment.Notes+"	N	Y"+
                        Environment.NewLine);
                        foreach(Commerce.PaymentReference reference in payment.PaymentRefrences){
                            billPaymentBuffer.Append("SPL		BILLPMT	"+strPaymentDate+
                            "	Accounts Payable	Order Number:"+reference.Order.OrderNumber+"	"+reference.Amount.ToString()+"			N	"+
                            Environment.NewLine);
                        }
                        billPaymentBuffer.Append("ENDTRNS"+Environment.NewLine);
                    }
                    using(SqlCommand cmd=new SqlCommand(@"/* insert exportFileAudit for Quickbooks IFF export plugin (payments) */
                    insert into exportFileAudit (exportFileAuditId, exportFileId, exportFileName, controlId, exportDate, controlIdType)
                    values (newId(), @exportFileId, @fileName, @paymentId, @exportDate, @controlIdType)",cn,trans)) {
                        cmd.Parameters.Add("@paymentId",SqlDbType.UniqueIdentifier).Value=new Guid(paymentId.ToString());
                        cmd.Parameters.Add("@controlIdType",SqlDbType.UniqueIdentifier).Value=new Guid(paymentControlId);
                        cmd.Parameters.Add("@exportFileId",SqlDbType.UniqueIdentifier).Value=new Guid(controlId);
                        cmd.Parameters.Add("@fileName",SqlDbType.VarChar).Value=fileName;
                        cmd.Parameters.Add("@exportDate",SqlDbType.DateTime).Value=exportDate;
                        cmd.ExecuteNonQuery();
                    }
                } catch(Exception ex) {
                    /* somthing didn't work correctly*/
                    ex.Message.Debug(0);
                }
            }
            /*
            * orders
            */
            this.Message="Creating Order Files.";
            ("Quickbooks 10 Export: " + this.Message).Debug(10);
            foreach(int orderId in orderIds) {
                try {
                    /* get the order */
                    Commerce.Order order = Commerce.Order.GetOrderByOrderId(orderId,cn,trans);
                    /* create the export string and validate it before adding it to the exportFileAudit table */
                    bool customer = order.User.AccountType==0;
                    string fileName;
                    if(customer) {
                        fileName=invoiceFileName;
                    } else {
                        fileName=billFileName;
                    }
                    if(customer) {
            /*
            * INVOICE
            *
            !TRNS	TRNSID	TRNSTYPE	DATE	ACCNT	NAME	CLASS	AMOUNT	DOCNUM	MEMO	CLEAR	TOPRINT	NAMEISTAXABLE	DUEDATE	TERMS	PAYMETH	SHIPVIA	SHIPDATE	REP	FOB	PONUM	INVMEMO	ADDR1	ADDR2	ADDR3	ADDR4	ADDR5	SADDR1	SADDR2	SADDR3	SADDR4	SADDR5	TOSEND	ISAJE	OTHER1
            !SPL	SPLID	TRNSTYPE	DATE	ACCNT	NAME	CLASS	AMOUNT	DOCNUM	MEMO	CLEAR	QNTY	PRICE	INVITEM	PAYMETH	TAXABLE	EXTRA	VATCODE	VATRATE	VATAMOUNT	VALADJ	SERVICEDATE	TAXCODE	TAXRATE	TAXAMOUNT	TAXITEM	OTHER2	OTHER3	REIMBEXP
            !ENDTRNS
            !ACCNT	NAME	REFNUM	ACCNTTYPE	ACCNUM	CURRENCY
            !INVITEM	NAME	INVITEMTYPE	DESC	PURCHASEDESC	ACCNT	ASSETACCNT	COGSACCNT	PRICE	COST	TAXABLE	PAYMETH	TAXVEND	TAXDIST	PREFVEND	REORDERPOINT	EXTRA	CUSTFLD1	CUSTFLD2	CUSTFLD3	CUSTFLD4	CUSTFLD5	DEP_TYPE	ISPASSEDTHRU	HIDDEN
            !CUST	NAME	BADDR1	BADDR2	BADDR3	BADDR4	BADDR5	COMPANYNAME	FIRSTNAME	MIDINIT	LASTNAME	CONT1	EMAIL	PHONE1	FAXNUM	SALUTATION	FIRSTNAME	MIDINIT	LASTNAME	CONT2	PHONE2	CTYPE	SADDR1	SADDR2	SADDR3	SADDR4	SADDR5
            !VEND	NAME	ADDR1	ADDR2	ADDR3	ADDR4	ADDR5	COMPANYNAME	CONT1	EMAIL	PHONE1	FAXNUM	PRINTAS	SALUTATION	FIRSTNAME	MIDINIT	LASTNAME	CONT2	PHONE2	VTYPE
            !OTHERNAME	NAME	BADDR1	BADDR2	BADDR3	BADDR4	BADDR5	COMPANYNAME	CONT1	EMAIL	PHONE1	FAXNUM	SALUTATION	FIRSTNAME	MIDINIT	LASTNAME	CONT2	PHONE2
            !EMP	NAME	ADDR1	ADDR2	ADDR3	ADDR4	ADDR5	FIRSTNAME	MIDINIT	LASTNAME	CITY	STATE	ZIP
            *
            *
            TRNS		INVOICE	4/5/2011	Accounts Receivable	Clay Design		59.66	48ZC			N	N	4/5/2011									Debbie Gizicki 25659 Kinyon	Taylor, MI 48044				Carrah Wilczynski 21805 E. Sunset Dr.	Macomb, MI 48044		Y
            SPL		INVOICE	4/5/2011	51100			-12.76		UPS Ground Tracking: Shipped On:		-1	12.76	Shipping		N				0.00			Non	0.00	0.00
            SPL		INVOICE	4/5/2011	25501			0		Tax		-1	0	Tax		N				0.00			Non	0.00	0.00
            SPL		INVOICE	4/5/2011	47900			-27.95		2 Quart Bowl		-1	27.95	454.N		N				0.00			Non	0.00	0.00
            SPL		INVOICE	4/5/2011	47900			-18.95		Ice Cream Bowl		-1	18.95	395.STIC		N				0.00			Non	0.00	0.00
            ENDTRNS
            */
                        string strExpAcct;
                        if(order.User.PurchaseAccount.Length>0){
                            strExpAcct = order.User.PurchaseAccount;
                        }else{
                            strExpAcct= defaultExportToAccount;
                        }
                        string strShippingDetails = "";
                        /* if there was at least one shipment, show that shipment */
                        if(order.Shipments.Count>0){
                            StringBuilder tl = new StringBuilder();
                            foreach(Commerce.Shipment shipment in order.Shipments){
                                tl.Append(shipment.Tracking);
                            }
                            strShippingDetails=string.Format("{0} Tracking:{1} Shipped On:{2}",order.ShipToAddress.Rate.Name,
                            string.Join(tl.ToString(),","),order.Shipments[0].DateShipped);
                        }
                        /* invoice */
                        string strOrderDate = order.OrderDate.ToString("MM/dd/yyyy");
                        string strShippingTotal = (order.ShippingTotal).ToString();
                        string strShippingTotalNeg = (order.ShippingTotal * -1).ToString();
                        string strTaxTotal = (order.TaxTotal).ToString();
                        string strTaxTotalNeg = (order.TaxTotal*-1).ToString();
                        string acctName = order.User.Handle;
                        if(acctName.Length==0){
                            /* if the acct name is blank use the Id # */
                            acctName = order.User.UserId.ToString();
                        }
                        string transType = "CASH SALE";
                        string dpAcct = "Undeposited Funds";
                        if(order.Term.Accrued){
                            transType = "INVOICE";
                            dpAcct = "Accounts Receivable";
                        }
                        /* header */
                        invoiceFileBuffer.Append("TRNS		"+transType+"	"+strOrderDate+
                        "	"+dpAcct+"	" +
                        acctName + "		" +
                        order.GrandTotal.ToString() + "	" +
                        order.OrderNumber+"		"+order.OrderNumber+"	N	N	"+
                        strOrderDate + "							" +
                        order.PurchaseOrder + "		" +
                        order.BillToAddress.FirstName + " " +
                        order.BillToAddress.LastName + " " +
                        order.BillToAddress.Address1 + " " +
                        order.BillToAddress.Address2 + "	" +
                        order.BillToAddress.City + ", " + order.BillToAddress.State + " " + order.BillToAddress.Zip + "				" +
                        order.ShipToAddress.FirstName + " " + order.ShipToAddress.LastName + " " +
                        order.ShipToAddress.Address1 + " " + order.ShipToAddress.Address2 + "	" +
                        order.ShipToAddress.City + ", " +
                        order.ShipToAddress.State + " " +
                        order.ShipToAddress.Zip + "		Y		" +Environment.NewLine);
                        /* line items */
                        foreach(Commerce.Line line in order.Lines){
                            invoiceFileBuffer.Append("SPL		"+transType+"	" + strOrderDate + "	" + line.Item.RevenueAccount +
                            "			"  + ((line.Price*line.Qty)*-1).ToString() + "		" + line.Item.ShortDescription +
                            "		" + (line.Qty*-1).ToString() + "	" + line.Price.ToString() + "	" + line.ItemNumber +
                            "		N				0.00			Non	0.00	0.00				"+Environment.NewLine);
                        }
                        /* items that go into the header in Rendition but go into a line item in quickbooks */
                        invoiceFileBuffer.Append("SPL		"+transType+"	"+strOrderDate+"	"+shippingRevAcct+"			"+
                        strShippingTotalNeg+"		"+strShippingDetails+"		-1	"+strShippingTotal+
                        "	"+"Shipping"+"		N				0.00			Non	0.00	0.00				"+
                        Environment.NewLine);

                        invoiceFileBuffer.Append("SPL		"+transType+"	"+strOrderDate+"	"+taxRevAcct+"			"+strTaxTotalNeg+"		"+
                        "Tax"+"		-1	"+strTaxTotal+"	"+"Tax"+"		N				0.00			Non	0.00	0.00				"+
                        Environment.NewLine);

                        invoiceFileBuffer.Append("SPL		"+transType+"	"+strOrderDate+"	"+discRevAcct+
                        "			"+order.Discount+"		"+"Discount"+"		-1	"+(order.Discount*-1)+
                        "	"+"Discount"+"		N				0.00			Non	0.00	0.00				"+
                        Environment.NewLine);
                        invoiceFileBuffer.Append("ENDTRNS"+Environment.NewLine);
                    } else {
            /*
            * PURCHASE ORDER
            *
            *
            !TRNS	TRNSID	TRNSTYPE	DATE	ACCNT	NAME	CLASS	AMOUNT	DOCNUM	MEMO	CLEAR	TOPRINT	ADDR5	DUEDATE	TERMS
            !SPL	SPLID	TRNSTYPE	DATE	ACCNT	NAME	CLASS	AMOUNT	DOCNUM	MEMO	CLEAR	QNTY	REIMBEXP	SERVICEDATE	OTHER2
            !ENDTRNS
            *
            *
            TRNS		BILL	7/16/98	Accounts Payable	Bayshore Water		-59.25			N	N		8/15/98	Net 30
            SPL		BILL	7/16/98	Utilities:Water			59.25			N		NOTHING	0/0/0
            ENDTRNS
            *
            */
                        string acctName = order.User.Handle;
                        if(acctName.Length==0){
                            /* if the acct name is blank use the Id # */
                            acctName = order.User.UserId.ToString();
                        }
                        string strOrderDate = order.OrderDate.ToString("MM/dd/yyyy");
                        string strDueDate = order.DeliverBy.ToString("MM/dd/yyyy");
                        billFileBuffer.Append("TRNS		BILL	"+strOrderDate+"	Accounts Payable	"+
                        order.UserId.ToString()+"		"+(order.GrandTotal*-1)+"			N	N		"+strDueDate+"	"+order.Term.Name+
                        Environment.NewLine);
                        foreach(Commerce.Line line in order.Lines){
                            billFileBuffer.Append("SPL		BILL	"+strOrderDate+"	"+line.Item.ItemNumber + ":" + line.Item.ShortDescription +
                            "			"+(line.Price*line.Qty)+"			N		NOTHING	0/0/0	"+
                            Environment.NewLine);
                        }
                        billFileBuffer.Append("ENDTRNS"+Environment.NewLine);
                    }
                    using(SqlCommand cmd=new SqlCommand(@"/* insert exportFileAudit for Quickbooks IFF export plugin (orders) */
                        insert into exportFileAudit (exportFileAuditId, exportFileId, exportFileName, controlId, exportDate, controlIdType)
                        values (newId(), @exportFileId, @fileName, @orderId, @exportDate, @controlIdType)",cn,trans)) {
                        cmd.Parameters.Add("@orderId",System.Data.SqlDbType.Int).Value=orderId;
                        cmd.Parameters.Add("@controlIdType",SqlDbType.UniqueIdentifier).Value=new Guid(orderControlId);
                        cmd.Parameters.Add("@exportFileId",SqlDbType.UniqueIdentifier).Value=new Guid(controlId);
                        cmd.Parameters.Add("@fileName",SqlDbType.VarChar).Value=fileName;
                        cmd.Parameters.Add("@exportDate",SqlDbType.DateTime).Value=exportDate;
                        cmd.ExecuteNonQuery();
                    }
                } catch(Exception ex) {
                    /* somthing didn't work correctly*/
                    Error = -1;
                    Message = string.Format("Error exporting to quickbooks:{0}",ex.Message);
                    Admin.AddFlag("0","order",orderId.ToString(),string.Format("Error exporting to Quickbooks -> <br>{0}",ex.Message));
                    ex.Message.Debug(0);
                }

            }
            if(Error!=0) {
                /* an error occured, roll back all transactions and prevent output of any files */
                trans.Rollback(transactionName);
            } else {
                this.Message="Writing buffers to disk.";
                ("Quickbooks 10 Export: "+this.Message).Debug(10);
                /* output files when there is data */
                if(billFileBuffer.Length>0) {
                    File.WriteAllText(Path.GetFullPath(outputPath).ToString()+billFileName,
                    billFileHeader+billFileBuffer.ToString());
                }
                if(invoiceFileBuffer.Length>0) {
                    File.WriteAllText(Path.GetFullPath(outputPath).ToString()+invoiceFileName,
                    invoiceFileHeader+invoiceFileBuffer.ToString());
                }
                if(billPaymentBuffer.Length>0) {
                    File.WriteAllText(Path.GetFullPath(outputPath).ToString()+bill_paymentFileName,
                    billPaymentHeader+billPaymentBuffer.ToString());
                }
                if(customerPaymentBuffer.Length>0) {
                    File.WriteAllText(Path.GetFullPath(outputPath).ToString()+customer_paymentFileName,
                    customerPaymentHeader+customerPaymentBuffer.ToString());
                }
                this.Message = "Last export: " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss");
                ("Quickbooks 10 Export: "+this.Message).Debug(10);
                try{
                    /* sometimes there's just not a trasaction, how can I check? more work thats how! */
                    if(paymentIds.Count>0||orderIds.Count>0){
                        trans.Commit();
                    }
                }catch{}
                cn.Close();
            }
        }