Use delegate from multiple classes and methods

49 views Asked by At

How can I send values between different methods from other classes?

I have different classes which controls products on a website. So I have a classes for products, categories, images etc. From the Product-class I have a method to delete a product which calls the Images-class to delete the images from the product. I would like to show the progress of the images which are deleted and afterwards continue deleting the product details or other attachments suchs as pdf-files. But there are other methods from other classes which can call the Images-class to delete images or just 1 images. From this point on, I have a form where I can delete a product where I would like to show the progress on a label. Also, most methods are async and the classes containing a public delegate ProgressUpdate(int counterProduct, int counterTotal, string text) and a Public event ProgressUpdate onProgressUpdate.

In my form I have:

public async Task<bool> deleteProducts(List<int> products)
{
    foreach (var product in products)
    {
        Products prdct = new Products();
        var isProductDeleted = await Products.deleteProduct(product);
        if (isProductDeleted)
        {
            var isDeleted = await I.DeleteImages(product);
        }
    }
    return true;
} 

In the Products-class:

class Products
{
public static async Task<bool> deleteProduct(int idProduct, int idShop = 1)
{
    if (idProduct > 0)
    {
        string query = "SELECT * FROM ps_product WHERE id_product = " + idProduct + ";";
        Database db = new Database();
        DataTable table = new DataTable();
        table = db.SelectWebsiteQuery(query);
        if(table.Rows.Count > 0)
        {
            //Things to delete
            //First check if this product is not assigned to an order
            //ps_product :Check
            //ps_product_attachment : check
            //ps_product_carrier : check
            //ps_product_lang : check
            //ps_product_sale : check
            //ps_product_shop : check
            //ps_product_supplier : check
            //ps_product_tag : check
            //ps_revws_criterion : Not necessary
            //ps_revws_criterion_category : Not necessary
            //ps_revws_criterion_lang : Not necessary
            //ps_revws_criterion_product : check
            //ps_revws_review : ok
            //ps_revws_review_grade : ok
            //ps_revws_review_image : ok
            //ps_revws_review_reaction : ok
            //ps_search_index and update ps_search_word
            //ps_specific_price : ok
            //ps_specific_price_priority : ok
            //ps_stock_available : ok
            //ps_stock_mvt
            //ps_image
            //ps_image_lang : ok
            //ps_image_shop
            //ps_feature_product
            //ps_category_product
            int id_product = Convert.ToInt32(table.Rows[0]["id_product"]);
            int id_supplier = Convert.ToInt32(table.Rows[0]["id_supplier"]);
            int id_category_default = Convert.ToInt32(table.Rows[0]["id_category_default"]);
            DataTable productDelete = new DataTable();
            //Check if this product has been ordered. If so, you can't delete it because it won't be visible in the order history
            query = "SELECT * FROM ps_order_detail WHERE product_id = " + idProduct + ";";
            productDelete = db.SelectWebsiteQuery(query);
            if(productDelete.Rows.Count == 0)
            {
                //First delete the images
                query = "SELECT id_image FROM ps_image WHERE id_product = " + id_product + ";";
                productDelete = db.SelectWebsiteQuery(query);
                
                if(db.InsertWebsiteQuery("DELETE FROM ps_product WHERE id_product = " + idProduct + ";") == 1)
                {
                    query = "SELECT attachment FROM ps_product_attachment WHERE id_product = " + idProduct + ";";
                    productDelete = db.SelectWebsiteQuery(query);
                    if(productDelete.Rows.Count > 0)
                    {
                        for(int a = 0; a < productDelete.Rows.Count; a++)
                        {
                            string attachmentName = productDelete.Rows[a]["attachment"].ToString();
                            await Ftp.DeleteFile(Properties.Settings.Default.FtpWebHost, Properties.Settings.Default.FtpWebUsername, Properties.Settings.Default.FtpWebPassword,
                                           Properties.Settings.Default.DownloadPath, attachmentName, Properties.Settings.Default.FtpWebSsh);
                        }
                    }
                    db.InsertWebsiteQuery("DELETE FROM ps_product_carrier WHERE id_product = " + idProduct + ";");
                    db.InsertWebsiteQuery("DELETE FROM ps_product_lang WHERE id_product = " + idProduct + ";");
                    db.InsertWebsiteQuery("DELETE FROM ps_product_sale WHERE id_product = " + idProduct + ";");
                    db.InsertWebsiteQuery("DELETE FROM ps_product_shop WHERE id_product = " + idProduct + ";");
                    db.InsertWebsiteQuery("DELETE FROM ps_product_supplier WHERE id_product = " + idProduct + ";");
                    db.InsertWebsiteQuery("DELETE FROM ps_product_tag WHERE id_product = " + idProduct + ";");
                    db.InsertWebsiteQuery("DELETE FROM ps_revws_criterion_product WHERE id_product = " + idProduct + ";");
                    db.InsertWebsiteQuery("DELETE FROM ps_specific_price WHERE id_product = " + idProduct + ";");
                    db.InsertWebsiteQuery("DELETE FROM ps_specific_price_priority WHERE id_product = " + idProduct + ";");
                    db.InsertWebsiteQuery("DELETE FROM ps_stock_available WHERE id_product = " + idProduct + ";");
                    query = "SELECT * FROM ps_image WHERE id_product = " + idProduct + ";";
                    table = db.SelectWebsiteQuery(query);
                    for(int i = 0; i < table.Rows.Count; i++)
                    {
                        int idImage = Convert.ToInt32(table.Rows[i]["id_image"]);
                        db.InsertWebsiteQuery("DELETE FROM ps_image_lang WHERE id_image = " + idImage + ";");
                        db.InsertWebsiteQuery("DELETE FROM ps_image_shop WHERE id_product = " + idProduct + " AND id_image = " + idImage + " AND id_shop = " + idShop + ";");
                    }

                    //Now delete all images
                    // From here I would like to have a response from the Images-class of the progress...
                    Images images = new Images();
                    var isDeleted = await images.DeleteImages(idProduct);

                    //Reorder product position
                    Category category = new Category();
                    category.reOrderProductCategory(idProduct);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}
}

And in my Images-class:

class Images
{
    //Thread shit
    public delegate void ProgressUpdate(int counterProduct, int counterTotal, string text);
    public event ProgressUpdate onProgressUpdate;
    public bool CancelThread = false;
public async Task<bool> DeleteImages(int idProduct = 0, int idImage = 0, int idCategory = 0)
{
    if (idProduct > 0 && idImage > 0 && idCategory > 0)
    {
        List<string> imageNames = new List<string>();
        Database db = new Database();
        string query = "";
        DataTable table = new DataTable();

        //First load the image-names from the image_type table depending on idProduct and idImage or idCategory
        query = "SELECT `name` FROM ps_image_type WHERE " + (idCategory > 0 ? "categories" : "products" ) + " = 1;";
        table = db.SelectWebsiteQuery(query);
        if (table.Rows.Count > 0)
        {
            //Load the names in the list
            for(int i = 0; i < table.Rows.Count; i++)
            {
                string imageName = table.Rows[i]["name"].ToString();
                imageName = imageName.Trim();
                imageNames.Add(imageName);
            }

            //Delete all images from product
            if (idProduct > 0 && idImage < 1 && idCategory < 1)
            {
                onProgressUpdate?.Invoke(0, 0, "Getting images to delete...");
                query = "SELECT id_image FROM ps_image WHERE id_product = " + idProduct + ";";
                table = db.SelectWebsiteQuery(query);
                if (table.Rows.Count > 0)
                {
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        string imagePath = Properties.Settings.Default.FtpImagePath;
                        int id_image = Convert.ToInt32(table.Rows[i]["id_image"].ToString());
                        string productImagePath = GetImagePath(id_image, imagePath);
                        for(int n = 0; n < imageNames.Count; n++)
                        {
                            string name = imageNames[n].ToString();
                            if(n == 0)
                            {
                                onProgressUpdate?.Invoke(idProduct, table.Rows.Count, "Deleting image: " + id_image.ToString() + ".jpg");
                                await Ftp.DeleteFile(Properties.Settings.Default.FtpWebHost, Properties.Settings.Default.FtpWebUsername, Properties.Settings.Default.FtpWebPassword, productImagePath,
                                    id_image.ToString() + ".jpg", Properties.Settings.Default.FtpWebSsh);
                            }
                            await Ftp.DeleteFile(Properties.Settings.Default.FtpWebHost, Properties.Settings.Default.FtpWebUsername, Properties.Settings.Default.FtpWebPassword, productImagePath,
                                    id_image.ToString() + "-" + name + ".jpg", Properties.Settings.Default.FtpWebSsh);
                            onProgressUpdate?.Invoke(idProduct, table.Rows.Count, "Deleting image: " + id_image.ToString() + "-" + name + ".jpg");
                        }
                    }
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else if (idProduct < 1 && idImage > 0 && idCategory < 1)//Delete a selected image
            {
                string imagePath = Properties.Settings.Default.FtpImagePath;
                int id_image = idImage;
                string productImagePath = GetImagePath(id_image, imagePath);
                for (int n = 0; n < imageNames.Count; n++)
                {
                    string name = imageNames[n].ToString();
                    if (n == 0)
                    {
                        await Ftp.DeleteFile(Properties.Settings.Default.FtpWebHost, Properties.Settings.Default.FtpWebUsername, Properties.Settings.Default.FtpWebPassword, productImagePath,
                            id_image.ToString() + ".jpg", Properties.Settings.Default.FtpWebSsh);
                    }
                    await Ftp.DeleteFile(Properties.Settings.Default.FtpWebHost, Properties.Settings.Default.FtpWebUsername, Properties.Settings.Default.FtpWebPassword, productImagePath,
                            id_image.ToString() + "-" + name + ".jpg", Properties.Settings.Default.FtpWebSsh);
                }
                return true;
            }
            else
            {
                string imagePath = Properties.Settings.Default.FtpCategoryPath;
                int id_category = idCategory;
                string categoryImagePath = GetImagePath(id_category, imagePath);
                for (int n = 0; n < imageNames.Count; n++)
                {
                    string name = imageNames[n].ToString();
                    if (n == 0)
                    {
                        await Ftp.DeleteFile(Properties.Settings.Default.FtpWebHost, Properties.Settings.Default.FtpWebUsername, Properties.Settings.Default.FtpWebPassword, categoryImagePath,
                            id_category.ToString() + ".jpg", Properties.Settings.Default.FtpWebSsh);
                    }
                    await Ftp.DeleteFile(Properties.Settings.Default.FtpWebHost, Properties.Settings.Default.FtpWebUsername, Properties.Settings.Default.FtpWebPassword, categoryImagePath,
                            id_category.ToString() + "-" + name + ".jpg", Properties.Settings.Default.FtpWebSsh);
                }
                return true;
            }
        }
        else
        {
            await Task.Run(async () => await Email.sendEmail(Properties.Settings.Default.EmailLogAddress, "No image types found for the given values in DeleteImages", 
                                                       "No names found for the image-types with image-type: " + (idCategory > 0 ? "categories." : "products."), true, ""));
            return false;
        }
    }
    else
    {
        return false;
    }
}
}
1

There are 1 answers

0
Paul Albers On

I already found how to do this from other classes. Here is a little example. In your form button click:

private async void btnTest_Click(object sender, EventArgs e)
{
    Counter counter = new Counter();
    counter.onProgressUpdate += new Counter.ProgressUpdate(C_onProgressUpdate);
    var isCounting = await counter.CountNumbers();
}

private void C_onProgressUpdate(int progress)
{
    base.Invoke((Action)delegate
    {
        lblValue.Text = progress.ToString();
    });
}

In the first class named Counter:

public delegate void ProgressUpdate(int counter);
public event ProgressUpdate onProgressUpdate;
public async Task<bool> CountNumbers()
{
    for(int i = 0; i < 50; i++)
    {
        await Task.Delay(100);
        onProgressUpdate?.Invoke(i);
        if(i == 20)
        {
            CounterSecond counterSecond = new CounterSecond();
            counterSecond.onProgressUpdate += CounterSecond_onProgressUpdate;
            await counterSecond.countNext();
        }
    }
    return true;
}

private void CounterSecond_onProgressUpdate(int counter)
{
    if(onProgressUpdate != null)
    {
        onProgressUpdate(counter);
    }
}

In your second class named CounterSecond.

public delegate void ProgressUpdate(int counter);
public event ProgressUpdate onProgressUpdate;

public async Task<bool> countNext()
{
    for (int i = 100; i < 150; i++)
    {

        await Task.Delay(100);
        onProgressUpdate?.Invoke(i);
    }
    return true;
}