Programming     Travel Logs     Life Is Good     Surfing Online     About Me
Embrace accountability, and take business risks under your own name. Society will reward you with responsibility, equity, and leverage.
-Naval Ravikant
2018-05-03 20:45:49

Copy this link when reproducing:
http://www.casperlee.com/en/y/blog/52

Just like before, let's take it easy and watch a video first. This video was shot by me last week at the Sea World in Shenzhen. And it is about a very beautiful show of a music fountain.

There is a main function that we have not implemented: Delete Document. Let's see how to do it in this section.

/Images/20161214/02.jpg

1. Open the main form in the main project, and double click on the "Delete" button to add an OnClick event handler function.

        private void btnDelete_Click(object sender, EventArgs e)
{
if (lvResult.SelectedItems.Count == 0)
{
return;
}

if (MessageBox.Show(
this,
"Are you sure?",
"Confirm",
MessageBoxButtons.YesNo) == DialogResult.No)
{
return;
}

foreach (ListViewItem item in lvResult.SelectedItems)
{
ResourceEx rx = (ResourceEx)item.Tag;
ResourceBll.Instance.DelResource(rx);
lvResult.Items.Remove(item);
}

MessageBox.Show(this, "Done!");
}

2. Open the file "ResourceBll.cs" in the Bll project and add a function "DelResource".

        public void DelResource(ResourceEx aResouce)
{
CreateHandler(true);
handler.DelResource(aResouce);
}

3. Here is the code of the "CreateHandler" function.

        private void CreateHandler(bool aSupportFulltextSearch)
{
if ((handler == null)
|| (handler is FulltextResourceHandler != aSupportFulltextSearch))
{
handler = aSupportFulltextSearch ?
new FulltextResourceHandler() : new ResourceHandler();
}
}

4. Open the file "ResourceHandler.cs" in the Bll project and add a function "DelResource".

        public virtual void DelResource(ResourceEx aResource)
{
using (ResourceManageEntities rme = new ResourceManageEntities())
{
Resource r = rme.Resources.Single<Resource>(x => x.ID == aResource.ID);
if (r != null)
{
CFileHandler.Instance.DeleteFile(r.FileName);
rme.Resources.Remove(r);
rme.SaveChanges();
}
}
}

5. Open the file "CFileHandler.cs" in the Library project, and add a function "DeleteFile".

        public void DeleteFile(string aFileName)
{
if (!File.Exists(aFileName))
{
throw new CException(CException.EXP_WILL_NOT_HAPPEN, "The specified file does not exist!");
}

FileHeader header;
using (FileStream fsInput = new FileStream(aFileName, FileMode.Open))
{
BinaryReader br = new BinaryReader(fsInput);
header = ReadFileHeader(br);
}

if (!string.IsNullOrEmpty(header.NextFile))
{
string nextFile = Path.Combine(Path.GetDirectoryName(aFileName), header.NextFile);
DeleteFile(nextFile);
}

File.Delete(aFileName);
}

6. Finished.