Dailycode.info

Short solution for short problems

Write HTML content to file

Not so very hard. The only tricky part is when there are IFrames on the page.

string
html;
using (WebClient client = new WebClient())
{
    client.UseDefaultCredentials = true;
    html = client.DownloadString("http://dailycode.info/dailycardgames/#/home");
    using (FileStream fs = new FileStream(@"d:\temp\files\test" + DateTime.Now.Ticks.ToString() + ".htm", FileMode.OpenOrCreate))
    {
        using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
        {
            w.WriteLine(html);
        }
    }
}

Then I noticed that in my page (not the one from the example above) there were iframes. And they were not loaded. 

So I had to also download the iframes, save them to a file and replace the url of the iframe to the url of the file.

Also I noticed that for example the umlaut ö was not shown correctly, so I had to include the UTF8 encoding in the download as well as in the file writer:

At the end it looked like this:

string html;
using (WebClient client = new WebClient())
{
    client.UseDefaultCredentials = true;
    client.Encoding = Encoding.UTF8;
    html = client.DownloadString("http://dailycode.info/dailycardgames/#/home");
 
    MatchCollection iframes = Regex.Matches(html, "<iframe.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase);
           
    int i = 0;
    foreach (Match m in iframes)
    {
        string url = m.Groups[1].Value;
        string iframe = client.DownloadString("http://dailycode.info/dailycardgames/" + url);
        iframe = iframe.Replace(@"../../images", @"D:\temp\images");
        var iframehtml = @"d:\temp\files\testiframe_"+i+"_" + DateTime.Now.Ticks.ToString() + ".htm";
        using (FileStream fs = new FileStream(iframehtml, FileMode.OpenOrCreate))
        {
            using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
            {
                w.WriteLine(iframe);
            }
        }
 
        html = html.Replace(url, iframehtml);
        i++;
    }
}
           
html = html.Replace(@"../images", @"D:\temp\images");
           
using (FileStream fs = new FileStream(@"d:\temp\files\test" + DateTime.Now.Ticks.ToString() + ".htm", FileMode.OpenOrCreate))
{
    using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
    {
        w.WriteLine(html);
    }
}

As you can see I also replace the images location to a offline location. 



How to read an email adress (mail box) from an Exchange 2007 or 2010 server and download email attachments?

For this I created a very simple WPF program (Source code attached at the bottom of this post) that will read a certain email address and process some items that have a certain subject. It will then download all the attachments of the items to the local disk. In the beginning I had some trouble finding the attachments of the items, but this was because I didn’t force a Load on the items. This will load all attachment information. (Lazy Loading I guess)

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);

 

    //You can pass credentials of the creadetials running the program have no access to the mail box

    //service.Credentials = new NetworkCredential( "{Active Directory ID}", "{Password}", "{Domain Name}" );

 

    //Provide the mail box to read

    service.AutodiscoverUrl("mark@dailycode.info");

 

    //Create a filter for the mails returned, in this case only the mails with SendFilesID= in the subject will be returned

    SearchFilter searchFilter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "SendFilesID=");

 

    //Return the first 10 items

    FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox,searchFilter,new ItemView(10));

           

    try

    {

        //Loop over the items

        foreach (Item item in findResults.Items)

        {

            //Show result

            txtResult.Text += item.Subject +Environment.NewLine;

            //This load is needed to fill all the properties of the item, if you do not use this, attachment information will be empty

            item.Load();

            //Check if the item has attachments

            if (item.HasAttachments)

            {

                //Loop over the attachments

                foreach (Attachment attachment in item.Attachments)

                {

                    //Check if the attachemnts is a file

                    if (attachment is FileAttachment)

                    {

                        if (!Directory.Exists(("C:\\TEMP\\Attachments")))

                        {

                            Directory.CreateDirectory("C:\\TEMP\\Attachments");

                        }

                        FileAttachment fileAttachment = attachment as FileAttachment;

                        // Load the file attachment into memory

                        fileAttachment.Load();

                        Console.WriteLine("Attachment name: " + fileAttachment.Name);

                        // Stream attachment contents into a file.

                        Stream theStream = File.Create("C:\\TEMP\\Attachments\\" + fileAttachment.Name); //new FileStream("D:\\Downloads\\Attachments\\" + fileAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite);

                        fileAttachment.Load(theStream);

                        theStream.Close();

                        theStream.Dispose();

                    }

                    else // Attachment is an item attachment.

                    {

                        // Load attachment into memory and write out the subject.

                        ItemAttachment itemAttachment = attachment as ItemAttachment;

                        itemAttachment.Load();

                        Console.WriteLine("Subject: " + itemAttachment.Item.Subject);

                    }

                }

            }

        }

    }

    catch (Exception er)

    {

        MessageBox.Show(er.Message);

    }

}

 

 

TestReadEmail.zip (17.67 kb)


Media control database version 1

I created a small WPF application that can handle all your hard copy media like CD's, DVD's, Blue ray, records, books etc.

It wil lhelp you keep track of things when you lend out media and find them.

See more of this here.

If you like to get the source code to see the WPF/MVVM code, no problem, simply contact me and I'll provide it.

Data is stored in XML. I used linq to query the data and WPF and MVVM to show the data.


Directory structure generator version 1.1

I made some adjustements to the directory structure generator which have lead to new version. The major change is that I do the generation in a seperate thread. Now I can update the info during the process, the main thread is not blocked. It is also possible to stop the porcess whenever you like.

I added some extra features which can be nice. E.g. sorting on date, show modifydate in result, ...

Here is a screenshots of the latest version:

The exe file and source files can be requested.

You can read here how it all started.

 


Free movie, CD and books database part 2

The first version is almost ready to be published. Here's a screenshot of the configuration part.

As you can see, you can select an automatic backup. You can manually backup and restore files. Also you can disable functions, for example if you are not using the movie database:

Only the tesing fase and then the first version will be released. When you are using them, all data is stored in a format that is supported for future versions. so start using it as soon as it becomes available. then you can get the new version just as free as you are getting this one!

Read part 1.


Self updating windows program part 2

In part 1 I explained how to write and implement a self updating windows program. The functionality was simple. Just before I close the program to be updated, I open the “update.bat“ file. Then I close the program. The bat file first pings to create a delay and after the ping it copies the new files to the directory. When its finished it will open the application again.
 
Because the interaction with the user is not so great, although I did not receive any complaints, I decided to improve this part of the application.
 
After some thinking I came up with the idea to create an updater program which can be used for multiple programs. So it had to be configurable.
 
 
 
The only thing you have to do is to copy the updater.exe and its configuration file to your solution. Make sure it is copied to the bin folder. Just add it to your solution and right-click on the files and choose properties. Then you will see the property copy to output directory. Set this property to: Copy always. Then you fill in the path in the configuration file. The configuration file could look something like this:
 
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="UpdateFilesPath" value="\\fileserver\updates\myprogram\latestversion\"/>
  </appSettings>
</configuration>
 
Then in the directory where the new files are placed, you’ll have to add an XML file called:updateInfo.xml with the following format:
 
<?xml version="1.0" standalone="yes"?>
<UpdateInfoDS xmlns="http://tempuri.org/UpdateInfoDS.xsd">
  <UpdateInfo>
    <ApplicationName>MyProgram</ApplicationName>
    <NewVersion>2.1.1.2</NewVersion>
    <ExtraInfo>Test version for update</ExtraInfo>
    <DeletePrevVersion>false</DeletePrevVersion>
  </UpdateInfo>
</UpdateInfoDS>
 
So here we can set the parameters of the updater. The new version and extra info parameters are simply to inform the user during update about what is being updated. The application name is shown on the tool as well, but is also used to check if the program to be updated is still in use. So it is important this is exactly the same is the exe you are trying to update.
The delete previous version (DeletePrevVersion) parameter is like it suggests: deleting all the files of the previous version.
 
To check if a new version is needed and to start the updater is similar as in part 1, but I will explain it again:
 
Because I’m working on a network with a database, I’ll check the database for a new version:
 
Assembly asm = Assembly.GetExecutingAssembly();
//Check registration and version
if (CheckRegistration(asm.GetName().Version.ToString()))
  
If there is a newer version then the current version of the program I will start an update:
 
System.Diagnostics.Process.Start(Application.StartupPath + @"\Updater.exe");
 
After I started the updater program, I’ll write some information to the database and close the application. The updater will wait until the program is closed until it starts the update.
This check is performed like this:
 
bool into = false;
string updatePath = ConfigurationSettings.AppSettings["UpdateFilesPath"];
int counter = 0;
while (!into)
{
    try
    {
        File.Copy(updatePath + @"\" + appName + ".exe", appName + ".exe", true);
        into = true;
    }
    catch
    {
        if (counter > 10)
        {
            return;
        }
        else
  {
            System.Threading.Thread.Sleep(500);
            counter++;
        }
    }
}
 
 
The deletion an copying of the files are done in a seperate thread, so it doesn't interfear with the GUI. The progress is set with thread safe methods. Before the update starts, I count the number of files to be copied and use this to set the progress bar limit. So it will give you a windows like information, if there is a files in the upload that is much bigger then the rest, the progress will not be as accurate. But still it give a better view then nothing, or just a wiating arrow.
When the copy is successful the program will go on to copy all files and if requested first delete all old files. The only files that are not deleted and copied over are the files of the updater itself. So it is really important that your updater is working really good and tested through several times. The update files have to be on the network, I'm currently working on an update of this program that enables you to place the update files on the internet. Then I should rewrite the File.Copy part.
 
That’s why I look at the updater not as a part of any solution but a separate program that can be used throughout all kinds of windows applications.
 
 

 


Directory structure generator

Many people have a certain logic in the way they build up their files system, and so they should. Sometimes you want to view this structure or export it because you want to use it for some kind of purpose. Then you will have a hard time in windows getting the structure in an organized way to a file or excel sheet.

 

For this reason I created a tool that helps you export a directory structure. It started out just exporting the structure if the directories and files, but now you can use checkboxes to add more information to the export.

You can:

  • Choose to see only file or dir names or the complete path.
  • Choose the depth of the search. (0 is only the root directory) 
  • Choose to show the size of the files.
  • Then for extra information on the top right you can see the number of files and directories that are shown. 

There is a new version available for download. You can find more info here in part 2. 

You can download this project latest version as an executable and/or the source files to get the function you need out of it.

 

 

 

 


Free movie, books and CD database part 1

Recently I started a new project, for personal use. I have a large collection of CD's and DVD's, this taking up more and more place. So now I was looking for software to keep an inventory of all these multimedia. I could find some, but the most interesting where not free. So I decided to make my own. This is a really nice porject in which I try some new stuff. When it is ready I will make it as a free download including the source code. For now you it will cover 3 types of multimedia: Audio CD's, Movies and books. There is a build in lend out system and some other cool stuff. I choose not to overload the objects with to much properties.

Here's a first look at the program:

I store all data in XML files. When data is first called I cache it, so the program runs smoothly. Since it is only text, it will not take to much memory.  

The caching is something I'm looking into with much interest. Before you start caching, you'll have to look into what to cache and when. For example, you could load all data at program startup, but then the startup takes long. The program I'm making consists of 3 big parts, Audio, Video and Books. I will create the system so that you can disable and enable these functionalities, so this makes caching more complicated. It's really fun to think of the best and most performant ways to cache.

What I also will implement in the system is an online update. I got some ideas in my head, just trying them out as soon as the first version of the program is almost ready. It's offcourse important to have the update procedure ready before I will release the first version.

I can assure you that you will find updates on this program on regular basis. It's a hobby!

So the first version is ready for publication. You will find it soon as a download on this site. The last step is testing and user manual generation. My wife will do the end user testing and I will generete a short manual.

Read more about this in the second part 2. 

Greetings and God bless this world!

 


Downloads

I created a downloads page because there were several demands for a demo project.

The first download is a demo project of the directshow library. I show how to take a picture and adjust video settings quickly.

Here's a screenshot of the program:

I'm so sorry I didn't shaved. Please forgive me ;-)

Here's the link: http://www.dailycode.net/blog/page/Downloads.aspx

The little picturebox on the top left displays the camera stream, the large one shows the picture you've taken. The reason why I look so funny on the little box is that I'm holdong the webcam in one hand and trying to perform a alt-printscreen with the other hand. :-) The examples above are taken with a Microsoft webcam. As you can see the results are very good. If you have an older webcam, read on, this might help you...

When your camera is not showing up, try lowering the resolution.  

//const int VIDEOWIDTH = 1600; // Depends on video device caps
//const int VIDEOHEIGHT = 1200; // Depends on video device caps
const int VIDEOWIDTH = 640; // Depends on video device caps
const int VIDEOHEIGHT = 480; // Depends on video device caps

I tested the program with a very old webcam, who only supported 640*480. then I adjusted the brightness and this is what it looked like: