Saturday, March 5, 2011

File uploading in chunks using HttpHandler and HttpWebRequest

How Do I? File uploading in chunks using HttpHandler and HttpWebRequest


This is a sample code that shows how to upload file using HttpHandler in chunks. This may not seems like a very good idea in isolation but this could help when creating a file upload control in Silverlight. I already have an article that shows how to upload file using web service in chunk. You can read this article here. When talk about file uploading using web service, it has many disadvantages like 1- it has a limit of sending and receiving data and 2- it pads data that increase the sending data, to name a few problems.

HttpHandlers are better in many ways; this technique could be used to enable huge files. It will understand the entire authentication and authorization constrains already implemented in your web application.
This article has two distinct parts
1- How to send data in chunks using HttpWebRequest
2- How to receive and save data in HttpHandler

Sending data in chunks
The implementation of HttpWebRequest is very simple. It has the following steps
1- Open a file
2- Start reading a chunk
3- Convert the chunk in Base64 String
4- Send the chunk to HttpHandler along with some basic file information e.g. file name

HttpWebRequest will post data to HttpHandler because of data limitation and sercurity of data in a Key-Value pair.

And here is the code
Function that will convert the file into chunk requests

private void ConvertToChunks()
{
 //Open file
 string file = MapPath("~/temp/1.xps");
 FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
 //Chunk size that will be sent to Server
 int chunkSize = 1024;
 // Unique file name
 string fileName = Guid.NewGuid() + Path.GetExtension(file);
 int totalChunks = (int)Math.Ceiling((double)fileStream.Length / chunkSize);
 // Loop through the whole stream and send it chunk by chunk;
  for (int i = 0; i < totalChunks; i++)
  {
    int startIndex = i * chunkSize;
    int endIndex = (int)(startIndex + chunkSize > fileStream.Length ?   fileStream.Length : startIndex + chunkSize);
    int length = endIndex - startIndex;

    byte[] bytes = new byte[length];
    fileStream.Read(bytes, 0, bytes.Length);
    ChunkRequest(fileName, bytes);
  }
}

Function that will send the chunk to httpHandler
private void ChunkRequest(string fileName,byte[] buffer)
{
 //Request url, Method=post Length and data.
 string requestURL = "http://localhost:63654/hello.ashx";
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
 request.Method = "POST";
 request.ContentType = "application/x-www-form-urlencoded";

 // Chunk(buffer) is converted to Base64 string that will be convert to Bytes on  the handler.
 string requestParameters = @"fileName=" + fileName +
"&data=" + HttpUtility.UrlEncode( Convert.ToBase64String(buffer) );

 // finally whole request will be converted to bytes that will be transferred to HttpHandler
 byte[] byteData = Encoding.UTF8.GetBytes(requestParameters);

 request.ContentLength = byteData.Length;

 Stream writer = request.GetRequestStream();
 writer.Write(byteData, 0, byteData.Length);
 writer.Close();
// here we will receive the response from HttpHandler
 StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream());
 string strResponse = stIn.ReadToEnd();
 stIn.Close();
}

Receiving and saving Chunk data in HttpHandler
It will
1- Receive the chunk and file information
2- Convert back the chunk to byte[] from Base64 string
3- Save the chunk by
a. Creating a new file if file not existed
b. Opening the existing file

Here is the Code

Function that will receive the request in HttpHandler
public void ProcessRequest(HttpContext context)
{
 //write your handler implementation here.

 string fileName = context.Request.Params["fileName"].ToString();
 byte[] buffer = Convert.FromBase64String ( context.Request.Form["data"]);
 SaveFile(fileName, buffer);
}
Function that will Save the file

public void SaveFile(string fileName, byte[] buffer)
{
 string Path = HttpContext.Current.Server.MapPath("~/upload") +"\\"+ fileName;
 FileStream writer = new FileStream(Path,File.Exists(Path)?FileMode.Append:FileMode.Create, FileAccess.Write);

 writer.Write(buffer, 0, buffer.Length);
 writer.Close();
}

To use HttpHandler, it must be configured in web.conf like shown below
<add verb="*" path="*.ashx" type="handlertest.IISHandler1, handlertest"/>

Hope this will help , Please click here to download the sample application. Please see the Default.aspx.cs for HttpWebRequest section and IISHandler1.cs for HttpHandler section.

100 comments:

  1. string requestURL = "http://localhost:63654/hello.ashx";

    What is ?

    ReplyDelete
  2. what is what? didnt understand your question

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. sorry, hello.ashx gets from handlertest.IISHandler1. just didnt understand.
    Very very nice method! Thanks.

    ReplyDelete
  6. but
    string requestURL = "http://" + Context.Request.Url.Authority + "hello.ashx";
    correctly, imho

    ReplyDelete
  7. Hi Sach, This article is just to show you how to do it and in no way it is complete or accurate. You are correct that it should be as you wrote.

    ReplyDelete
  8. use string file = MapPath("~/temp/1.xps"); i.e. if file place to server its work fine to all browsers,
    but if file need to browse and select from local disk and upload
    - this working ONLY with IE (7-9)! (sorry for my english)

    ReplyDelete
  9. hi,

    are you setting 'isreusable' property to true or false?
    how does this code work for concurrent requests?

    please clarify.

    thanks

    ReplyDelete
  10. @Jg vimlan IsReusable is only relevant when your class has instance variables. As far as general concurrency is concerned, you should look carefully at the file handling and check that there is no possible contention.

    @Mamoon, as you state, the overhead of web services is not necessary here. However, this implementation fails to practically decrease this overhead as you still base64 encode the binary stream. This is not necessary. The HTTP is perfectly capable on transmitting byte streams.

    By encoding, the overhead is actually greater than MOTM or binary XML.

    Lastly, if you're going to send base64, you encode it to bytes (!) using the ASCII encoder, UTF-8 is nor necessary.

    HTH

    ReplyDelete
  11. The link to download the sample application no longer works.

    ReplyDelete
  12. The link to download the sample application no longer works.

    ReplyDelete
  13. Useful article , my working group some time ago saw http://pdf.ac/8pXYyW to export pdf , It's extremely uncomplicated to get the hang of and it's handy . I saw they are offering a 30 day trial now

    ReplyDelete
  14. I had the issue that the chunking would reads the same 1024 bytes of the file for each chunk instead of getting the next 1024 bytes.

    So to get it to work I have set the position of the fileStream in ConvertToChunks():

    fileStream.Position = startIndex;

    Regardless of that, this article has been really useful, Thank you

    ReplyDelete


  15. Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. Dot Net Training in chennai | Dot Net Training institute in velachery

    ReplyDelete
  16. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    Digital Marketing online training

    full stack developer training in pune

    full stack developer training in annanagar

    full stack developer training in tambaram

    ReplyDelete
  17. I'm here representing the visitors and readers of your own website say many thanks for many remarkable
    python training in rajajinagar
    Python training in btm

    ReplyDelete
  18. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs online Training

    angularjs Training in marathahalli

    ReplyDelete
  19. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    Java training in Chennai

    Java training in Bangalore

    ReplyDelete
  20. Outstanding blog thanks for sharing such wonderful blog with us ,after long time came across such knowlegeble blog. keep sharing such informative blog with us.
    redmi note service center in chennai
    redmi service center in velachery
    redmi service center in t nagar

    ReplyDelete
  21. Nice blog! But I can't download the sample application.

    ReplyDelete
  22. Outstanding blog thanks for sharing such wonderful blog with us ,after long time came across such knowlegeble blog. keep sharing such informative blog with us.
    big data hadoop training in chennai | big data training and placement in chennai | big data certification in chennai

    ReplyDelete

  23. thanks for your details it's very useful and amazing.your article is very nice and excellentweb design company in velachery

    ReplyDelete
  24. The blog... which you have posted is more impressive... thanks for sharing with us...
    web design company in velachery

    ReplyDelete
  25. Very correct statistics furnished, Thanks a lot for sharing such beneficial data.
    todaypk movies
    ............................................................

    ReplyDelete
  26. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.

    learn amazon web services
    aws course in bangalore

    ReplyDelete
  27. azure tutorial I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.

    ReplyDelete

  28. I am very happy when read this blog post because blog post written in good manner and write on good topic. Thanks for sharing valuable information about Data Science Course.

    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  29. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.AWS training in Chennai

    AWS Online Training in Chennai

    AWS training in Bangalore

    AWS training in Hyderabad

    AWS training in Coimbatore

    AWS training

    AWS online training

    ReplyDelete
  30. I had a chance to get some useful and unique information, I love your writing style very much, it was so good to read and useful to improve my knowledge as updated one, keep blogging…Digital Marketing Training in Chennai

    Digital Marketing Training in Velachery

    Digital Marketing Training in Tambaram

    Digital Marketing Training in Porur
    <
    Digital Marketing Training in Omr
    Digital Marketing Training in Annanagar

    ReplyDelete
  31. Outstanding blog thanks for sharing such wonderful blog with us ,after long time came across such knowlegeble blog. keep sharing such informative blog with us.
    DevOps Training in Chennai

    DevOps Course in Chennai

    ReplyDelete
  32. Thank you for blogging this content in a practical way.its helps me to send and receive data in chunks

    Python Training in chennai | Python Classes in Chennai

    ReplyDelete
  33. Thanks for the Valuable information.Really useful information. Thank you so much for sharing. It will help everyone.

    SASVBA is recognized as the best machine learning training in Delhi. Whether you are a project manager, college student, or IT student, Professionals are the best machine learning institute in Delhi, providing the best learning environment, experienced machine learning instructors, and flexible training programs for the entire module.

    FOR ORE INFO:

    ReplyDelete
  34. Thanks for posting the best information and the blog is very helpful.
    Amazon Web Services Training in Chennai

    ReplyDelete
  35. You need to be a part of a contest for one of the best websites online. I’m going to recommend this website!
    data scientist training and placement in hyderabad

    ReplyDelete
  36. Keto Pills are the most popular type of weight loss product and chances are you’ve probably seen advertisements for keto products by now. These keto pure diet pills may help enhance your weight loss, boost your energy levels, and can make it easier for you to stick to your keto diet. Many of the most popular keto products contain exogenous ketones – ketones made outside of the body. These ketones are the fuel that your body burns instead of carbohydrates when you are on the keto diet. Check now the full Keto pure diet pills reviews for clear your doubt with full information. Some keto products may contain one or many other natural ingredients that may help boost your metabolism in addition to these exogenous ketones.

    ReplyDelete
  37. Skinnyfit is a brand renowned for creating collagen and powder supplements for weight loss. It has manufactured and worked on a vast number of weight-loss products, peptides, and collagen. Super Youth is a collagen peptide powder intended to promote more youthful skin, a healthy weight, and strong bones and joints. Check now Skinnyfit Super Youth Reviews. There has been more recent research into the potential health benefits of taking collagen, including for healthy hair, skin, nails, joint and bone health, gut health, and weight loss.

    ReplyDelete
  38. Very interesting article with detailed explanation. Thanks for sharing. keep up the good work Angular training in Chennai

    ReplyDelete
  39. Thanksfor posting the best information and the blog is very good.data science training in udaipur

    ReplyDelete
  40. Магазин спортивного питания, официальный интернет-сайт которого доступен по адресу: SportsNutrition-24.Com, реализует большой ассортимент товаров, которые принесут пользу и заслуги как профессиональным спортсменам, так и любителям. Интернет-магазин осуществляет свою деятельность уже большое количество лет, предоставляя клиентам со всей России качественное питание для спорта, а помимо этого витамины и особые препараты - Креатин. Спортпит представляет собой категорию продуктов, которая призвана не только улучшить спортивные достижения, но и благоприятно влияет на здоровье организма. Подобное питание вводится в повседневный рацион с целью получения микро- и макроэлементов, витаминов, аминокислот и белков, а кроме этого прочих недостающих веществ. Не секрет, что организм спортсмена в процессе наращивания мышечной массы и адаптации к повышенным нагрузкам, остро нуждается в должном количестве полезных веществ. При этом, даже правильное питание и употребление растительной, а помимо этого животной пищи - не гарантирует того, что организм получил нужные аминокислоты либо белки. Чего нельзя сказать о качественном спортивном питании. Об ассортименте товаров Интернет-магазин "SportsNutrition-24.Com" продает качественную продукцию, которая прошла ряд проверок и получила сертификаты качества. Посетив магазин, заказчики смогут найти для себя товары из следующих категорий: - L-карнитинг (Л-карнитин) представляет собой вещество, родственное витамину B, синтез которого осуществляется в организме; - гейнеры, представляющие собой, белково-углеводные консистенции; - BCAA - средства, содержащие в своем составе три важные аминокислоты, стимулирующие рост мышечной массы; - протеин - чистый белок, употреблять который вы можете в виде коктейлей; - современные аминокислоты; - а кроме этого ряд других товаров (нитробустеры, жиросжигатели, особые препараты, хондропротекторы, бустеры гормона роста, тестобустеры и многое другое). Об оплате и доставке Интернет-магазин "SportsNutrition-24.Com" предлагает большое обилие товаров, которое в полной мере способно удовлетворить проф и начинающих спортсменов, включая любителей. Большой опыт дозволил организации сделать связь с наикрупнейшими поставщиками и изготовителями питания для спорта, что позволило сделать политику цен гибкой, а цены - демократичными! К примеру, аминокислоты либо гейнер заказать можно по цене, которая на 10-20% ниже, чем у конкурентов. Оплата возможна как наличным, так и безналичным расчетом. Магазин предлагает большой выбор методов оплаты, включая оплату различными электронными платежными системами, а кроме этого дебетовыми и кредитными картами. Главный офис фирмы размещен в Санкт-Петербурге, но доставка товаров осуществляется во все населенные пункты РФ. Помимо самовывоза, получить товар вы можете при помощи любой транспортной фирмы, подобрать которую каждый клиент может в личном порядке.

    ReplyDelete
  41. Консоли от корпорации Microsoft не сразу захватили всемирную популярность и доверие игроков. 1-ая консоль под названием Xbox, вышедшая в далеком 2001 году, значительно уступала PlayStation 2 по количеству проданных приставок. Однако все изменилось с выходом Xbox 360 - консоли седьмого поколения, которая стала по-настоящему "народной" для жителей Рф и стран СНГ - Игры для Xbox 360 прошивка LT 3.0 торрент. Портал Ru-Xbox.Ru является пользующимся популярностью ресурсом в числе поклонников приставки, так как он предлагает игры для Xbox 360, которые поддерживают все имеющиеся версии прошивок - совсем бесплатно! Зачем играть на оригинальном железе, если есть эмуляторы? Для Xbox 360 игры выходили долгое время и представлены как посредственными проектами, так и хитами, многие из которых даже сейчас остаются эксклюзивными для это консоли. Некие гости, желающие сыграть в игры для Xbox 360, могут задать вопрос: для чего необходимы игры для прошитых Xbox 360 freeboot или разными версиями LT, если есть эмулятор? Рабочий эмулятор Xbox 360 хоть и существует, однако он просит производительного ПК, для покупки которого будет нужно вложить существенную сумму. К тому же, различные артефакты в виде исчезающих текстур, отсутствия некоторых графических эффектов и освещения - могут изрядно попортить впечатления об игре и отбить желание для ее предстоящего прохождения. Что предлагает этот веб-сайт? Наш интернет-сайт на сто процентов приурочен к играм для приставки Xbox 360. У нас вы можете совершенно бесплатно и без регистрации загрузить игры на Xbox 360 через торрент для следующих версий прошивок консоли: - FreeBoot; - LT 3.0; - LT 2.0; - LT 1.9. Каждая прошивка имеет свои особенности обхода интегрированной защиты. Потому, для запуска той или прочей игры потребуется скачать специальную ее версию, которая стопроцентно адаптирована под одну из четырех перечисленных выше прошивок. На нашем сайте вы можете без труда получить желаемый проект под подходящую прошивку, поскольку возле каждой игры находится название версии (FreeBoot, LT 3.0/2.0/1.9), под которую она приспособлена. Гостям данного ресурса доступна особая категория игр для 360-го, предназначенных для Kinect - специального дополнения, которое считывает все движения 1-го или нескольких игроков, и позволяет управлять с помощью их компьютерными персонажами. Большой выбор ПО Кроме способности скачать игры на Xbox 360 Freeboot или LT разных версий, здесь вы можете найти программное обеспечение для консоли от Майкрософт: - современные версии Dashboard, которые позволяют кастомизировать интерфейс консоли под свои нужды, сделав его более комфортным и нынешним; - браузеры; - просмотрщики файлов; - сохранения для игр; - темы для консоли; - программы, для конвертации образов и записи их на диск. Кроме перечисленного выше игры на Xbox 360 Freeboot можно запускать не с дисковых, а с USB и многих других носителей, используя программу x360key, которую вы можете достать на нашем веб-сайте. Посетителям доступно множество полезных статей, а также форум, где вы можете пообщаться с единомышленниками либо попросить совета у более опытнейших хозяев консоли.

    ReplyDelete
  42. Магазин спортивного питания, официальный портал которого доступен по адресу: SportsNutrition-24.Com, реализует большой ассортимент товаров, которые принесут пользу и заслуги как проф спортсменам, так и любителям. Интернет-магазин осуществляет свою деятельность уже многие годы, предоставляя клиентам со всей Рф высококачественное питание для спорта, а кроме этого витамины и особые препараты - sportsnutrition-24. Спортпит представляет собой категорию продуктов, которая призвана не только улучшить спортивные достижения, да и положительно влияет на здоровье организма. Схожее питание вводится в повседневный рацион с целью получения микро- и макроэлементов, витаминов, аминокислот и белков, а помимо этого многих других недостающих веществ. Не секрет, что организм спортсмена в процессе наращивания мышечной массы и адаптации к повышенным нагрузкам, остро нуждается в должном количестве полезных веществ. При всем этом, даже правильное питание и употребление растительной, а кроме этого животной пищи - не гарантирует того, что организм получил необходимые аминокислоты или белки. Чего нельзя сказать о качественном спортивном питании. Об ассортименте товаров Интернет-магазин "SportsNutrition-24.Com" реализует качественную продукцию, которая прошла ряд проверок и получила сертификаты качества. Посетив магазин, клиенты смогут подобрать себе товары из следующих категорий: - L-карнитинг (Л-карнитин) представляет собой вещество, схожее витамину B, синтез которого осуществляется в организме; - гейнеры, представляющие собой, белково-углеводные смеси; - BCAA - средства, содержащие в собственном составе три важнейшие аминокислоты, стимулирующие рост мышечной массы; - протеин - чистый белок, употреблять который можно в виде коктейлей; - разнообразные аминокислоты; - а кроме этого ряд прочих товаров (нитробустеры, жиросжигатели, специальные препараты, хондропротекторы, бустеры гормона роста, тестобустеры и все остальное). Об оплате и доставке Интернет-магазин "SportsNutrition-24.Com" предлагает огромное разнообразие товаров, которое в полной мере способно удовлетворить профессиональных и начинающих спортсменов, включая любителей. Большой опыт позволил компании сделать связь с крупнейшими поставщиками и производителями спортивного питания, что позволило сделать ценовую политику гибкой, а цены - демократичными! К примеру, аминокислоты или гейнер приобрести можно по стоимости, которая на 10-20% ниже, чем у конкурентов. Оплата возможна как наличным, так и безналичным расчетом. Магазин предлагает огромный выбор способов оплаты, включая оплату разными электронными платежными системами, а также дебетовыми и кредитными картами. Главный офис организации расположен в Санкт-Петербурге, однако доставка товаров осуществляется во все населенные пункты РФ. Кроме самовывоза, получить товар вы можете с помощью любой транспортной компании, найти которую каждый клиент может в индивидуальном порядке.

    ReplyDelete
  43. Informational blog and knowledgeable content. Keep update more blogs with us. And If you are looking for data science course training, then join AI Patasala Data Science Training in Hyderabad program.
    Data Science Certification Course in Hyderabad

    ReplyDelete
  44. Thank you for sharing this piece of code with us, It would be really helpful! best digital marketing training in Delhi

    ReplyDelete
  45. Thanks for sharing this blog . DevOps classes in Pune

    ReplyDelete
  46. Hello Blogger,
    This writeup is a valuable resource for anyone looking to implement file uploading in chunks using HttpHandler and HttpWebRequest. The detailed explanations, code examples, and practical considerations make it a comprehensive guide for developers aiming to achieve this functionality in their projects. Thank you for sharing.
    If anyone wants to build their career in the field of Data Analytics then chcek this article about best Data Analytics Courses in Pune:
    Data Analytics Courses in Pune

    ReplyDelete
  47. Thanks for sharing this sample code! I'm interested in learning more about file uploading using HttpHandler in chunks. I'll check out your other article as well.

    Data Analytics Courses In Bangalore

    ReplyDelete
  48. Thank you for the insightful advice. Excellent information. I really appreciate you sharing. All will benefit from it.
    Data Analytics Courses in Agra

    ReplyDelete
  49. File uploading in chunks using HttpHandler and HttpWebRequest is a powerful technique for efficiently transferring large files over HTTP, ensuring reliability and optimal performance. In the field of data analytics, Glasgow's Data Analytics courses empower professionals with the expertise to manage and analyze vast datasets, making informed decisions that drive business success in the modern data-driven landscape. Please also read Data Analytics courses in Glasgow

    ReplyDelete
  50. Your detailed explanation of file uploading in chunks using HttpHandler and HttpWebRequest is both comprehensive and insightful.
    Data analytics courses in new Jersey

    ReplyDelete
  51. The blog post is comprehensive and informative tutorial on how to upload file using HttpHandler in chunks. Thanks for providing informative content.
    data analyst courses in limerick

    ReplyDelete
  52. The step-by-step breakdown of the implementation, coupled with code snippets and explanations, showcases your commitment to making this technical topic accessible. Your attention to detail, from setting up the HttpHandler to handling the chunks and reconstructing the file, ensures that developers can follow along seamlessly. Digital Marketing Courses In Norwich

    ReplyDelete
  53. This detailed guide showcases a robust method for uploading large files via HttpHandler using HttpWebRequest. By breaking down the process into manageable chunks, this approach overcomes limitations in data transfer and security, leveraging HttpHandlers for efficient and secure transmission. It's a valuable resource for implementing file upload controls, especially in scenarios involving Silverlight applications, while addressing the constraints posed by web service-based uploads.
    Data Analytics courses in new york

    ReplyDelete
  54. Thanks a million for sharing this exceptional post. Your writing is not only informative but also eloquent. I'm truly impressed by the depth of research and the clarity of your presentation.
    Investment banking courses syllabus

    ReplyDelete
  55. Hey there! This article on file uploading in chunks using HttpHandler and HttpWebRequest is really informative. Uploading large files can sometimes be a challenge, but breaking them into smaller chunks can make the process more efficient. It's great to have a step-by-step guide on how to implement this technique. Thanks for sharing!
    Data analytics courses in Rohini

    ReplyDelete
  56. You can surely take pride in writing such wonderful thought provoking articles. You left me wondering about the topic! Wish to read some more writings from you.
    FICO training in Kolkata
    SAP training in Kolkata
    AWS training in Kolkata

    ReplyDelete
  57. After a long time, I have come across such a wonderful piece of writing. It is really informative as well as impressive. I really wish to read some more brilliant writings from you.
    SAP training in Mumbai
    Data Science training in Mumbai
    Data Science training in Pune
    SAP training in Pune

    ReplyDelete
  58. I particularly like the way how you have mentioned all the major points about the topic of the content in crisp points. Good work done! Thank you so much for the best work.
    SAP training in Mumbai

    ReplyDelete