C# Webservice Code Help/critique Follow

0
Avatar
Legacy Poster

Hello everyone,
 
I am just looking for some help getting my print method dialed in. I am getting some random errors when multiple people print at the exact same time.
The logs don't help to much and I am calling my web service via ajax.  Please give me an extra eye on something I may be doing in correctly as far as engines and taskques.
Thank you for any help.
The console message I am getting is this
 

                       System.InvalidOperationException: PrintLabels Web Service method name is not valid. at System.Web.Services.Protocols.HttpServerProtocol.Initialize() at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)

 

 

 
 
 public object[] PrintLabels(LabelDetails[] formVars)
    {
      
        string[] items = formVars.FormMultiple("selection[]");
        if (items == null)
        {
            outMessage.Add("No Items Selected");
            //return "No Items Selected";
            return outMessage.ToArray();
        } else {
            //Check if shipping info is set
            if (formVars.Form("txtCompany") == "" || formVars.Form("txtFirst") == "" || formVars.Form("txtLast") == "" || formVars.Form("txtAddress") == "" || formVars.Form("txtCity") == "" || formVars.Form("ddState") == "" || formVars.Form("txtZip") == "")
            {
                outMessage.Add("Missing Shipping Info");
                return outMessage.ToArray();
            }
            //Check for data input than we need to create a single engine(or check for engine) create a single taskmanager (or check for task manager) add task to queue. 
            //Need to figure out how to shutdown manager and engine
            using (Engine btEngine = new Engine(true))//Added true on 6/29
            {
                // Start the BarTender print engine. CHecking to see if the engine is busy if not start a new one
                if (!btEngine.IsProcessingCommandLines && !btEngine.IsPrinting)
                {
                    btEngine.Start();
                }
                string sPath = @"" + AppDomain.CurrentDomain.BaseDirectory + "temp";
                string file = Guid.NewGuid().ToString();
                if (File.Exists(sPath + "\\" + file + "3.txt") || File.Exists(sPath + "\\" + file + "3.jpg") || File.Exists(sPath + "\\" + file + "4.jpg") || File.Exists(sPath + "\\" + file + "4.txt"))
                {
                    file = Guid.NewGuid().ToString();
                }
                string fileName3 = sPath + "\\" + file + "3.jpg";
                string fileName4 = sPath  + "\\" + file + "4.jpg";
                string fileNameOnly3 = file + "3.jpg";
                string fileNameOnly4 = file + "4.jpg";
                string sFileName = file + ".jpg";
                
                string path3 = sPath + "\\" + file + "3.txt";
                string path4 = sPath + "\\" + file + "4.txt";
                //We need to two seperate text files one for 1/4 and one for 1/3
                if (!File.Exists(path3))
                {
                    //File.Create(path);
                    using (TextWriter tw = File.CreateText(path3))
                    {
                        //TextWriter tw = new StreamWriter(path);
                        List<string> list = new List<string>() { "\"itemDesc\"", "\"itemID\"", "\"copies\"", "\"price\"", "\"stock\"", "\"customer_code\"", "\"shopper\"", "\"company\"", "\"addy\"", "\"addy2\"", "\"listname\"" };
                        string commaSeparated = String.Join(",", list.ToArray());
                        tw.WriteLine(commaSeparated);
                        tw.Close();
                    }
                }
 
                if (!File.Exists(path4))
                {
                    using (TextWriter tw = File.CreateText(path4))
                    {
                        //TextWriter tw = new StreamWriter(path);
                        List<string> list = new List<string>() { "\"itemDesc\"", "\"itemID\"", "\"copies\"", "\"price\"", "\"stock\"", "\"customer_code\"", "\"shopper\"", "\"company\"", "\"addy\"", "\"addy2\"", "\"listname\"" };
                        string commaSeparated = String.Join(",", list.ToArray());
                        tw.WriteLine(commaSeparated);
                        tw.Close();
                    }
                }
 
                //2 seperate text files for 1/3 and 1/4
                TextFile textFile3 = new TextFile("Text File 1");//Must use same name as database that is connected through the label not the actual text file name
                // Provide a path to the text file.
                textFile3.FileName = path3;
                textFile3.Delimitation = DatabaseDelimitation.QuoteAndComma;
                textFile3.NumberOfFields = 11;//How many columns (itemDesc,itemID,copies, etc)
                textFile3.UseFieldNamesFromFirstRecord = true;
 
                TextFile textFile4 = new TextFile("Text File 1");//Must use same name as database that is connected through the label not the actual text file name
                // Provide a path to the text file.
                textFile4.FileName = path4;
                textFile4.Delimitation = DatabaseDelimitation.QuoteAndComma;
                textFile4.NumberOfFields = 11;//How many columns (itemDesc,itemID,copies, etc)
                textFile4.UseFieldNamesFromFirstRecord = true;
                
                using (TaskManager btTaskManager = new TaskManager())
                {
                    var priceCheck = formVars.Form("priceCheck");
                    var stockCheck = formVars.Form("stockCheck");
                    var customPartCheck = formVars.Form("customPartCheck");
                    LabelFormatDocument btFormat3;
                    LabelFormatDocument btFormat4;
                    //LabelFormatDocument btFormatShipping = btEngine.Documents.Open(@"c:\btLabels\StockRoomShipping.btw", "Lexmark C6160");
   
                    if (priceCheck == "1" && stockCheck == "1" && customPartCheck == "1")
                    {
                        //Load load all
                        btFormat3 = btEngine.Documents.Open(@"c:\btLabels\StockRoom3All.btw", "Lexmark C6160");//Must set a printer for the exportprintpreview to work
                        btFormat4 = btEngine.Documents.Open(@"c:\btLabels\StockRoom4All.btw", "Lexmark C6160");//Must set a printer for the exportprintpreview to work
                    }
                    else if (priceCheck == "1" && stockCheck == "0" && customPartCheck == "0")
                    {
                        //load price labels
                        btFormat3 = btEngine.Documents.Open(@"c:\btLabels\StockRoom3Price.btw", "Lexmark C6160");//Must set a printer for the exportprintpreview to work
                        btFormat4 = btEngine.Documents.Open(@"c:\btLabels\StockRoom4Price.btw", "Lexmark C6160");//Must set a printer for the exportprintpreview to work
                    }
                    else if (priceCheck == "0" && stockCheck == "1" && customPartCheck == "0")
                    {
                        //load Stock labels
                        btFormat3 = btEngine.Documents.Open(@"c:\btLabels\StockRoom3Stock.btw", "Lexmark C6160");//Must set a printer for the exportprintpreview to work
                        btFormat4 = btEngine.Documents.Open(@"c:\btLabels\StockRoom4Stock.btw", "Lexmark C6160");//Must set a printer for the exportprintpreview to work
                    }
                    else if (priceCheck == "0" && stockCheck == "0" && customPartCheck == "1")
                    {
                        //load customer labels
                        btFormat3 = btEngine.Documents.Open(@"c:\btLabels\StockRoom3CustomerCode.btw", "Lexmark C6160");//Must set a printer for the exportprintpreview to work
                        btFormat4 = btEngine.Documents.Open(@"c:\btLabels\StockRoom4CustomerCode.btw", "Lexmark C6160");//Must set a printer for the exportprintpreview to work
                    }
                    else if (priceCheck == "1" && stockCheck == "1" && customPartCheck == "0")
                    {
                        //load Price Stock labels
                        btFormat3 = btEngine.Documents.Open(@"c:\btLabels\StockRoom3PriceStock.btw", "Lexmark C6160");//Must set a printer for the exportprintpreview to work
                        btFormat4 = btEngine.Documents.Open(@"c:\btLabels\StockRoom4PriceStock.btw", "Lexmark C6160");//Must set a printer for the exportprintpreview to work
                    }
                    else if (priceCheck == "0" && stockCheck == "1" && customPartCheck == "1")
                    {
                        //load Customer Stock labels
                        btFormat3 = btEngine.Documents.Open(@"c:\btLabels\StockRoom3CustomerStock.btw", "Lexmark C6160");//Must set a printer for the exportprintpreview to work
                        btFormat4 = btEngine.Documents.Open(@"c:\btLabels\StockRoom4CustomerStock.btw", "Lexmark C6160");//Must set a printer for the exportprintpreview to work
                    }
                    else if (priceCheck == "1" && stockCheck == "0" && customPartCheck == "1")
                    {
                        //load Customer Price labels
                        btFormat3 = btEngine.Documents.Open(@"c:\btLabels\StockRoom3CustomerPrice.btw", "Lexmark C6160");//Must set a printer for the exportprintpreview to work
                        btFormat4 = btEngine.Documents.Open(@"c:\btLabels\StockRoom4CustomerPrice.btw", "Lexmark C6160");//Must set a printer for the exportprintpreview to work
                    }
                    else
                    {
                        //Load standard labels
                        btFormat3 = btEngine.Documents.Open(@"c:\btLabels\StockRoom3.btw", "Lexmark C6160");//Must set a printer for the exportprintpreview to work
                        btFormat4 = btEngine.Documents.Open(@"c:\btLabels\StockRoom4.btw", "Lexmark C6160");//Must set a printer for the exportprintpreview to work
                    }
                    
                   // btFormat3.SubStrings["templateSelect"].Value = "Template 1";
                    //Set these two globals so we know if its only 1x3 or 1x4 or both
                    var qty1x3Global = "";
                    var qty1x4Global = "";
                    // Start a TaskEngine. 1 only means 1 engine
 
                    // Start the task engines if necessary. 
                    if (btTaskManager.TaskEngines.Count == 0) { 
                        btTaskManager.Start(1);
                        //btTaskManager.Resize(3, 5000, false);
                    }
 
                    //Lets populate the shipping and ordered label
                    var txtCompany = formVars.Form("txtCompany");
                    var txtFirst = formVars.Form("txtFirst");
                    var txtLast = formVars.Form("txtLast");
                    var txtAddress = formVars.Form("txtAddress");
                    var txtCity = formVars.Form("txtCity");
                    var ddState = formVars.Form("ddState");
                    var txtZip = formVars.Form("txtZip");
                   
                    //Group these tasks
                    GroupTask groupTask = new GroupTask();
                    
                    groupTask.Name = formVars.Form("txtFirst") + " " + formVars.Form("txtLast") + " @ " + formVars.Form("txtCompany");
                   // groupTask.Add(new PrintLabelFormatTask(btFormatShipping));
                    int counterForShipping = 0;
                    int counterForShipping1x4 = 0;
                    foreach (string item in items)
                    {
                        //get the item code than the corresponding info for the label
                        //check if price is set
                        //check if customer part number is set
                        //check what label is set and the quantity
                        LabelDetails lbItem = new LabelDetails();
                        var qty1x3 = formVars.Form("qty1x3_" + item);
                        var qty1x4 = formVars.Form("qty1x4_" + item);
                        //var price = formVars.Form("price_" + item);
                        //var min = formVars.Form("stock_" + item);
                        var price = "";
                        var stock = "";
                        var customerPart = "";
                        var max = formVars.Form("max_" + item);
                        var partno = formVars.Form("partno_" + item);
                        var itemDesc = Server.UrlDecode(formVars.Form("itemDescription_" + item));
                        //Check for price, stock, and customer part
                        if (priceCheck == "1")
                        {
                            if (formVars.Form("price_" + item) != "" && formVars.Form("price_" + item) != "0")
                            {
                                price += "Price ";
                                price += formVars.Form("price_" + item);
                            }
                        }
                        if (stockCheck == "1")
                        {
 
                            if (formVars.Form("stock_" + item) != "" && formVars.Form("stock_" + item) != "0")
                            {
                                stock += "Stock ";
                                stock += formVars.Form("stock_" + item);
                            }
                        }
                        if (customPartCheck == "1")
                        {
                            customerPart = formVars.Form("partno_" + item);
                        }
 
                        //We have a match so lets populate the substrings on the labels
                        if (qty1x3 != "" && qty1x3 != "0")
                        {
                            //Set our global to have data so we know we need to print these labels
                            qty1x3Global += qty1x3;
                            try
                            {
                                TextWriter tww = new StreamWriter(path3, true);
                                List<string> list1 = new List<string>();
                                if (counterForShipping != 0 && counterForShipping != 1)//Only add shipping to first record
                                {
                                    list1 = new List<string>() { "\"" + itemDesc + "\"", "\"" + item + "\"", "\"" + qty1x3 + "\"", "\"" + price + "\"", "\"" + stock + "\"", "\"" + customerPart + "\"", "\"\"", "\"\"", "\"\"", "\"\"", "\"" + formVars.Form("listname") + "\"" };
                                 
                                }
                                if (counterForShipping == 0)//Row 2
                                {
                                    list1 = new List<string>() { "\"" + itemDesc + "\"", "\"" + item + "\"", "\"" + qty1x3 + "\"", "\"" + price + "\"", "\"" + stock + "\"", "\"" + customerPart + "\"", "\"" + txtFirst + " " + txtLast + "\"", "\"" + txtCompany + "\"", "\"" + txtAddress + "\"", "\"" + txtCity + ", " + ddState.ToUpper() + " " + txtZip + "\"", "\"" + formVars.Form("listname") + "\"" };
                                    ++counterForShipping;
                                }
                                else if (counterForShipping == 1)//Row 3
                                {
                                    list1 = new List<string>() { "\"" + itemDesc + "\"", "\"" + item + "\"", "\"" + qty1x3 + "\"", "\"" + price + "\"", "\"" + stock + "\"", "\"" + customerPart + "\"", "\"" + txtFirst + " " + txtLast + "\"", "\"" + txtCompany + "\"", "\"\"", "\"\"", "\"" + formVars.Form("listname") + "\"" };
                                    ++counterForShipping;
                                }
                                string commaSeparated1 = String.Join(",", list1.ToArray());
                                tww.WriteLine(commaSeparated1);
                                tww.Close();
                            }
                            catch (Exception e)
                            {
                                //path = e.Message;
                                outMessage.Add(e.Message);
                            }
                           
                        }
 
                        if (qty1x4 != "" && qty1x4 != "0")
                        {
                            //Set our global to have data so we know we need to print these labels
                            qty1x4Global += qty1x4;
                            try
                            {
                                TextWriter tww = new StreamWriter(path4, true);
                                List<string> list1 = new List<string>();
                                if (counterForShipping1x4 != 0 && counterForShipping1x4 != 1)//Only add shipping to first record
                                {
                                    list1 = new List<string>() { "\"" + itemDesc + "\"", "\"" + item + "\"", "\"" + qty1x4 + "\"", "\"" + price + "\"", "\"" + stock + "\"", "\"" + customerPart + "\"", "\"\"", "\"\"", "\"\"", "\"\"", "\"" + formVars.Form("listname") + "\"" };
                                }
                                if (counterForShipping1x4 == 0)//Row 2
                                {
                                    list1 = new List<string>() { "\"" + itemDesc + "\"", "\"" + item + "\"", "\"" + qty1x4 + "\"", "\"" + price + "\"", "\"" + stock + "\"", "\"" + customerPart + "\"", "\"" + txtFirst + " " + txtLast + "\"", "\"" + txtCompany + "\"", "\"" + txtAddress + "\"", "\"" + txtCity + ", " + ddState.ToUpper() + " " + txtZip + "\"", "\"" + formVars.Form("listname") + "\"" };
                                    ++counterForShipping1x4;
                                }
                                else if (counterForShipping1x4 == 1)//Row 3
                                {
                                    list1 = new List<string>() { "\"" + itemDesc + "\"", "\"" + item + "\"", "\"" + qty1x4 + "\"", "\"" + price + "\"", "\"" + stock + "\"", "\"" + customerPart + "\"", "\"" + txtFirst + " " + txtLast + "\"", "\"" + txtCompany + "\"", "\"\"", "\"\"", "\"" + formVars.Form("listname") + "\"" };
                                    ++counterForShipping1x4;
                                }
 
                                string commaSeparated1 = String.Join(",", list1.ToArray());
                                tww.WriteLine(commaSeparated1);
                                tww.Close();
                            }
                            catch (Exception e)
                            {
                                //path = e.Message;
                                outMessage.Add(e.Message);
                            }
                        }
 
                    }
                    //We have a match so lets populate the substrings on the labels
                    if (qty1x3Global != "" && qty1x3Global != "0")
                    {
                        // Set the database connection created above.
                        btFormat3.DatabaseConnections.SetDatabaseConnection(textFile3);
                        groupTask.Add(new PrintLabelFormatTask(btFormat3));
                    }
 
                    if (qty1x4Global != "" && qty1x4Global != "0")
                    {
                        // Set the database connection created above.
                        btFormat4.DatabaseConnections.SetDatabaseConnection(textFile4);
                        groupTask.Add(new PrintLabelFormatTask(btFormat4));
                    }
                  
                    // Close the current format without saving.
                    btFormat3.Close(SaveOptions.DoNotSaveChanges);
                    // Close the current format without saving.
                    btFormat4.Close(SaveOptions.DoNotSaveChanges);
                    //Task Events
                    foreach (Task task in groupTask)
                    {
                        task.Aborted += new EventHandler<TaskEventArgs>(task_Aborted);
                        task.ErrorOccurred += new EventHandler<TaskEventArgs>(task_ErrorOccurred);
                        task.Queued += new EventHandler<TaskEventArgs>(task_Queued);
                        task.Started += new EventHandler<TaskEventArgs>(task_Started);
                        task.Succeeded += new EventHandler<TaskEventArgs>(task_Succeeded);
                        task.TimedOut += new EventHandler<TaskEventArgs>(task_TimedOut);
                        task.Completed += new EventHandler<TaskEventArgs>(task_Completed);
                     
                    }
                    
                    // Submit the Task to the TaskQueue. 
                    TaskStatus btTaskStatus = btTaskManager.TaskQueue.QueueTask(groupTask);
                   
                   // TaskStatus btTaskStatus4 = btTaskManager.TaskQueue.QueueTask(btTask4);
                    // Stop the task engines as they finish up. 
                    //Once the tasks manager submits the task to the spool the task manager is no longer needed.
                    //We really don't check if the printer spool has finished printing
                    //If we really want the website to sit there and let the user know we could possibly do this
                    while (btTaskManager.TaskEngines.BusyCount > 0)
                    {
                        // Stop each engine if idle. 
                        foreach (TaskEngine e in btTaskManager.TaskEngines)
                        if (e.IsAlive && e.Status != TaskEngineStatus.Busy)
                            e.Stop(0, true);
                        System.Threading.Thread.Sleep(10000);
                    }
 
                    // The wait timeout is the maximum time we wait for the 
                    // asynchronous task above to finish before stopping. 
                    // Make sure that all engines are stopped. 
                    if (btTaskManager.TaskEngines.AliveCount > 0)
                        btTaskManager.Stop(10000, true);
 
                    //Delete files created
                   // File.Delete(path3);
                   // File.Delete(path4);
                    outMessage.Add(groupTask.Status.ToString());//Success or error
                }
 
 
                // Since the commandline is processed asynchronously, we must 
                // wait for printing to complete before stopping the engine. 
                while (btEngine.IsProcessingCommandLines || btEngine.IsPrinting)
                {
                    System.Threading.Thread.Sleep(10000);
                }
                btEngine.Stop();
            }
            //Send email to so they know to pick up and send the labels
            sendEmail(formVars.Form("txtFirst") + " " + formVars.Form("txtLast") + " @ " + formVars.Form("txtCompany"));
            return outMessage.ToArray();
        }
 
    }

Please sign in to leave a comment.