locked
What an executable (.exe) file contains... RRS feed

  • Question

  •   Hello.

      First of all I will tell you how I get the .exe file, publishing a program in VisualBasic:

    • Publish>Prerequisites> Unmark "Create setup program...";
    • Options>Deployment> Unmark "Use ".deploy" file extension";
    • Then Publish Now (to a folder path);
    • In the specified folder path, delete the ".application" file, open the folder "Application Files">[ProjectName] and delete everything except the executable file. (I don't think these files are really needed because the program works well from the ".exe" file. If they are needed sometimes for something, then tell me about that plz.)

      Now some questions:

    1. Will commented lines of code be compiled into the executable file? If yes, then why? Do that means that there are ways to open the executable back and see its Visual Basic code and comments?
    2. I saw somewhere a .exe file being called a "Binary File", so can binary files be converted into human-readable text? I did a program with some resources like images, icon and sounds and all worked well using the executable file alone. This seems to be because the executable contains all resources inside it, in binary too. Is this true?
    3. Are Settings saved in the executable too? Or it contains an instruction to read/write the saved Settings in the .config file in the same location as the executable? (I noticed that a .exe.config file was created when the program was using 1 Setting. But I changed it from the program and when I open the .config as .txt the setting value didn't changed!)

      Thank you for reading this and thank you for replies. I am learning programing using tutorials in the internet (in English, but my main language is Portuguese) and I think I may understand better what's happening by learning what Visual Studio does between the Form1.vb code and the binary that it creates when published.


    Greetings

    Wednesday, July 20, 2016 10:24 PM

Answers

  • Benur,

    You're asking questions with definitive answers so you should change this to a question rather than a discussion.

    I'll try to help here though:

    Commented code is ignored by the compiler. If it's XML documentation, that's all picked up and written to a file, but they're still considered comments and aren't usable so the compiler ignores them completely.

    What's created when you build it shows it to be an .exe file but in reality it's not - not in the traditional way at all. It's binary, yes - but it's MSIL (Microsoft Intermediate Language) which is why, if not obfuscated, it's so easy to break in (decompile) and see your code or something that can be used to create your code (sometimes verbatim).

    As for resources, I'm guessing you're concerned that someone might disassemble your .exe and get them? Well stop worrying - of course they will. It's not even that hard really.

    Settings are saved to and read back from an XML file (it's serialized from whatever it came from). I'm assuming you mean Application Settings but if not then explain more please?

    I hope that helps some. :)


    In the middle of difficulty ... lies opportunity. -- Albert Einstein

    • Marked as answer by Benur21 Friday, July 22, 2016 2:11 PM
    Wednesday, July 20, 2016 10:41 PM
  • Will commented lines of code be compiled into the executable file? If yes, then why? Do that means that there are ways to open the executable back and see its Visual Basic code and comments?

    Comments are not included with the executable.

    I saw somewhere a .exe file being called a "Binary File", so can binary files be converted into human-readable text? I did a program with some resources like images, icon and sounds and all worked well using the executable file alone. This seems to be because the executable contains all resources inside it, in binary too. Is this true?

    A binary file is just numbers, so it can be displayed in any numeric representation, such as hex.  Whether anyone can make any sense of it is a different question.  An image, for instance, can be extracted and reconstructed from the numbers - the only slightly tricky bit is finding the location in the binary file at which it is located.  Whether or not the executable contains all the resources depends on how you managed them - some are embedded, some are in different files.

    Are Settings saved in the executable too? Or it contains an instruction to read/write the saved Settings in the .config file in the same location as the executable? (I noticed that a .exe.config file was created when the program was using 1 Setting. But I changed it from the program and when I open the .config as .txt the setting value didn't changed!)

    Settings are saved into separate files created when the application first runs, or subsequently as required.  They are not saved at the same location as the executable, but at application data or user data.   The values in the config files that you saw are the default values that the settings files are created with.

    • Marked as answer by Benur21 Friday, July 22, 2016 2:12 PM
    Wednesday, July 20, 2016 11:30 PM
  • What is that different location? And why do the executable needs the config file close to it if it is only needed when there's no data? (use default when there's no current settings avaiable)

    See here.
    https://msdn.microsoft.com/en-us/library/a65txexh.aspx

    I don't understand the second point.  How is the application going to know the default values if they haven't been saved somewhere?

    I can't see that this has anything to do with your original question.

    • Marked as answer by Benur21 Friday, July 22, 2016 2:12 PM
    Thursday, July 21, 2016 9:33 PM

All replies

  • Benur,

    You're asking questions with definitive answers so you should change this to a question rather than a discussion.

    I'll try to help here though:

    Commented code is ignored by the compiler. If it's XML documentation, that's all picked up and written to a file, but they're still considered comments and aren't usable so the compiler ignores them completely.

    What's created when you build it shows it to be an .exe file but in reality it's not - not in the traditional way at all. It's binary, yes - but it's MSIL (Microsoft Intermediate Language) which is why, if not obfuscated, it's so easy to break in (decompile) and see your code or something that can be used to create your code (sometimes verbatim).

    As for resources, I'm guessing you're concerned that someone might disassemble your .exe and get them? Well stop worrying - of course they will. It's not even that hard really.

    Settings are saved to and read back from an XML file (it's serialized from whatever it came from). I'm assuming you mean Application Settings but if not then explain more please?

    I hope that helps some. :)


    In the middle of difficulty ... lies opportunity. -- Albert Einstein

    • Marked as answer by Benur21 Friday, July 22, 2016 2:11 PM
    Wednesday, July 20, 2016 10:41 PM

  •   I thought that because I have some questions and I want to understand What an executable file contains, this should be a discussion... But ok I change it.

    I hope it was helpful. I'm sure you have questions though?


    In the middle of difficulty ... lies opportunity. -- Albert Einstein

    Wednesday, July 20, 2016 11:11 PM
  •   I thought that because I have some questions and I want to understand What an executable file contains, this should be a discussion... But ok I change it.

    That depends if the executable is a non-obfuscated .Net executable or an unmanaged code executable.

    A non-obfuscated .Net executable can be opened in Notepad and string properties text can be read if any exists. .Net decompilers can decompile them.

    I suppose a .Net decompiler can decompile obfuscated .Net executables but I'm not certain about that.

    For UWP (Universal Windows Platform) apps I believe there is a method to compile them so the output executable would be some form of unmanaged code executable (to make it smaller and run faster removing unecessary overhead also I suppose) which probably would not be capable of being decompiled by a .Net decompiler such as Teleriks JustDecompile.

    Google search results for "Microsoft intermediate language"

    Compiling to MSIL

    Compiling Apps with .NET Native - From this link it looks like .Net Native is available for any app. I don't know if a .Net decompiler can decompile a .Net native executable or not.


    La vida loca

    Wednesday, July 20, 2016 11:27 PM
  • Will commented lines of code be compiled into the executable file? If yes, then why? Do that means that there are ways to open the executable back and see its Visual Basic code and comments?

    Comments are not included with the executable.

    I saw somewhere a .exe file being called a "Binary File", so can binary files be converted into human-readable text? I did a program with some resources like images, icon and sounds and all worked well using the executable file alone. This seems to be because the executable contains all resources inside it, in binary too. Is this true?

    A binary file is just numbers, so it can be displayed in any numeric representation, such as hex.  Whether anyone can make any sense of it is a different question.  An image, for instance, can be extracted and reconstructed from the numbers - the only slightly tricky bit is finding the location in the binary file at which it is located.  Whether or not the executable contains all the resources depends on how you managed them - some are embedded, some are in different files.

    Are Settings saved in the executable too? Or it contains an instruction to read/write the saved Settings in the .config file in the same location as the executable? (I noticed that a .exe.config file was created when the program was using 1 Setting. But I changed it from the program and when I open the .config as .txt the setting value didn't changed!)

    Settings are saved into separate files created when the application first runs, or subsequently as required.  They are not saved at the same location as the executable, but at application data or user data.   The values in the config files that you saw are the default values that the settings files are created with.

    • Marked as answer by Benur21 Friday, July 22, 2016 2:12 PM
    Wednesday, July 20, 2016 11:30 PM
  • Benur,

    You're asking questions with definitive answers so you should change this to a question rather than a discussion.

      I thought that because I have some questions and I want to understand What an executable file contains, this should be a discussion... But ok I change it.

      Yesterday I was prepairing a print to more quotings when something happened here ("Gateway" problem...) and I had no time to see what was happening. And IDK WHO IS MIGRATIONUSER 1! I WROTE THAT REPLY! I also had no time to change thread type. And how do I make multiple quotes in the same reply?

    Greetings



    • Edited by Benur21 Thursday, July 21, 2016 11:51 AM
    Thursday, July 21, 2016 11:49 AM

  • Settings are saved to and read back from an XML file (it's serialized from whatever it came from). I'm assuming you mean Application Settings but if not then explain more please?

      I mean this Settings:

    And can I just open that .config file (or xml or whatever) as a text file and change the Setting value, so the program will use the value that I changed to? I did a small program to test that and the .config was not changing even the program was saving the setting right.


    Greetings

    Thursday, July 21, 2016 12:00 PM

  •   I mean this Settings:

    And can I just open that .config file (or xml or whatever) as a text file and change the Setting value, so the program will use the value that I changed to? I did a small program to test that and the .config was not changing even the program was saving the setting right.


    Greetings

    It should work. I've seen others over the years report that it sometimes wouldn't but I could never reproduce it.

    I use my own way, but that's not really germane - Application Settings should work.


    In the middle of difficulty ... lies opportunity. -- Albert Einstein

    Thursday, July 21, 2016 12:04 PM
  • Benur, 

    The guys and girls who created .Net and there program languages had to handle many directives, for instance. 

    1. Make it easy to accept and to introduce
    2. Give the highest production
    3. Make it robust for a common end user to use in his organization. 

    They did not make it for one person. If you want your own behaviour, then there is much made around .Net which makes it completely tailored for you. You can Google for it and needs weeks to understand at least a little bit of it.

    However, be aware, everything has its price.  


    Success
    Cor



    Thursday, July 21, 2016 12:06 PM
  • They are not saved at the same location as the executable, but at application data or user data.

                                                                                                   Acamar

      Where is application data or user data? And why do the executable needs the .config close to it?

    Greetings

    Thursday, July 21, 2016 12:10 PM
  • Benur,

    You're straying from the original question(s).

    How about start a new question about Application Settings please.


    In the middle of difficulty ... lies opportunity. -- Albert Einstein

    Thursday, July 21, 2016 12:18 PM
  • And can I just open that .config file (or xml or whatever) as a text file and change the Setting value, so the program will use the value that I changed to? I did a small program to test that and the .config was not changing even the program was saving the setting right.

    See above.   You are probably looking at a config file for the executable, which contains the default settings, not the current settings.  Settings are saved at a different location.

    Thursday, July 21, 2016 12:42 PM

  • See above.   You are probably looking at a config file for the executable, which contains the default settings, not the current settings.  Settings are saved at a different location.

      What is that different location? And why do the executable needs the config file close to it if it is only needed when there's no data? (use default when there's no current settings avaiable)

    Greetings

    Thursday, July 21, 2016 12:50 PM
  • Benur,

    You're straying from the original question(s).

    How about start a new question about Application Settings please.


    In the middle of difficulty ... lies opportunity. -- Albert Einstein

      I don't like be creating threads for everything and that's why I choose Discussion for it, I want to understand how the executable works and what it needs to work and why. But I will try not to go too far from the thread title. And the questions about Settings are still about what instructions the executable contains to find the Settings values, then I'll stay here making more questions about what I find in the replies..

      And thanks all for all that replies until now :D


    Greetings

    Thursday, July 21, 2016 12:59 PM

  •   I don't like be creating threads for everything and that's why I choose Discussion for it, I want to understand how the executable works and what it needs to work and why. But I will try not to go too far from the thread title. And the questions about Settings are still about what instructions the executable contains to find the Settings values, then I'll stay here making more questions about what I find in the replies..

     

    If you want to discuss something you have to do that with persons with the same knowledge level of your own. 

    It makes no sense to discuss with persons on the Einstein level about algebra if you're still at kindergarten. I know many want to do that. 

    The Application Settings are as nearby the executable format as Melbourne to New York. 

    Therefore as long as you are not on the Einstein level, first ask questions.


    Success
    Cor


    Thursday, July 21, 2016 4:02 PM
  • What is that different location? And why do the executable needs the config file close to it if it is only needed when there's no data? (use default when there's no current settings avaiable)

    See here.
    https://msdn.microsoft.com/en-us/library/a65txexh.aspx

    I don't understand the second point.  How is the application going to know the default values if they haven't been saved somewhere?

    I can't see that this has anything to do with your original question.

    • Marked as answer by Benur21 Friday, July 22, 2016 2:12 PM
    Thursday, July 21, 2016 9:33 PM

  • I don't understand the second point.  How is the application going to know the default values if they haven't been saved somewhere?

      What if I write the default value in the code? And how do I make it save the Setting in the executable directory?

      And ok I will create new thread for this questions.

    UPDATE:

      Created: https://social.msdn.microsoft.com/Forums/vstudio/en-US/958bfaef-da06-4e8c-b6c5-e58e86ab023f/where-settings-are-saved?forum=vbgeneral


    Greetings


    • Edited by Benur21 Friday, July 22, 2016 2:23 PM
    Friday, July 22, 2016 12:59 PM

  • What's created when you build it shows it to be an .exe file but in reality it's not - not in the traditional way at all. It's binary, yes - but it's MSIL (Microsoft Intermediate Language) which is why, if not obfuscated, it's so easy to break in (decompile) and see your code or something that can be used to create your code (sometimes verbatim).

                                                                                                               Frank L. Smith

      Then how can I decompile the executable to see and edit? I want to change the path where it goes to save/load the Settings :P

    Greetings

    Friday, July 22, 2016 7:09 PM


  •   Then how can I decompile the executable to see and edit? I want to change the path where it goes to save/load the Settings :P

    Greetings

    Benur,

    I'm at work right now on a project, so I don't have a lot of time, but if you want me to show you how to decompile it then we can.

    What you said though - changing where things are saved to and thusly loaded from - that's not something you can change if you're using Application Settings (it's in dotNET, not the code that's decompiled).

    If you want to roll your own (which is what I do), then I'll explain that too, but it's not beginner material, so do give it thought. It can be done though - no matter the type (including your own types if you create them) so it's quite flexible.

    I'll have a look back in tomorrow.


    Some people succeed because they were destined to, but most people succeed because they were determined to.

    Friday, July 22, 2016 7:15 PM

  • (it's in dotNET, not the code that's decompiled)

                                                                                                          Frank L. Smith

      oh

      Then I'll create a shortcut on desktop to the folder where the Settings are currently saved (it will be easier to test projects and see what value is currently saved).

      I was also thinking in making my own DataSaver by creating a text file in the executable path and saving every variable on it like:

    variable1=234
    variable2=hello
    variable3=true

     but I'll need to study the commands that read a file, find where's the variable name plus the = and change that variable to the value next to it (or change). And this way would be easier to people hack a game or change any variable K_K, even if I change the extension they could just open it as a text file. If that happens then maybe I change the path to somewhere in the computer instead of in the same path as the executable.

      Thanks!


    Greetings

    Friday, July 22, 2016 7:38 PM


  •   oh

      Then I'll create a shortcut on desktop to the folder where the Settings are currently saved (it will be easier to test projects and see what value is currently saved).

      I was also thinking in making my own DataSaver by creating a text file in the executable path and saving every variable on it like:

    variable1=234
    variable2=hello
    variable3=true

     but I'll need to study the commands that read a file, find where's the variable name plus the = and change that variable to the value next to it (or change). And this way would be easier to people hack a game or change any variable K_K, even if I change the extension they could just open it as a text file. If that happens then maybe I change the path to somewhere in the computer instead of in the same path as the executable.

      Thanks!


    Greetings

    Don't do it that way - not if you want it really robust.

    Not everything can be easily used as a string. It's easier to do it the way that I'll show you, I just don't have time to get into it right now.

    I'll explain more tomorrow, but I do need to know what you want to save. Just like Application Settings, it's very specific so please explain what you want to save and later recall.

    I'll be back tomorrow.


    Some people succeed because they were destined to, but most people succeed because they were determined to.

    Friday, July 22, 2016 7:58 PM


  • I'll explain more tomorrow, but I do need to know what you want to save. Just like Application Settings, it's very specific so please explain what you want to save and later recall.

      I'm used* to see variables storing only numbers and other characters (translated to VB strings, integers and some others). But in VB I see that there's other value types that I don't understand so much for now. Because of that, I just want to know how to save variables as integers, strings, and maybe some others that allow decimals and very very big numbers.

      Thanks and I will wait for that "easier way" you are going to show me tomorrow.

      *in languages like Scratch and SmallBasic (where variables stores every value type [idk what about storing images, colours, files or whatever]).


    Thanks A LOT!!!

    Friday, July 22, 2016 8:51 PM
  • What if I write the default value in the code? And how do I make it save the Setting in the executable directory?

    You can change the value of a settings variable in code, but the default is what you specify in the Settings entry.

    You can write your own settings routine by following the details at the site I referred to above.  That allows you to override the location at which the files are stored.  That seems like a lot of work to duplicate something that has already been built for you.

    Friday, July 22, 2016 9:40 PM
  • Then how can I decompile the executable to see and edit? I want to change the path where it goes to save/load the Settings

    There's no need to decompile your code to see that - it is part of the application code that is created for you.

    Note that if you change the location then you must ensure it meets the required standards - available on any machine for any version of the OS, specific to the user or the application, specific to the application version, and not protected by security restrictions.  That is not an easy standard to meet.

    Friday, July 22, 2016 9:43 PM
  • Then I'll create a shortcut on desktop to the folder where the Settings are currently saved (it will be easier to test projects and see what value is currently saved).

    There's no point - just access the values from within the application to see what they are currently set at.  You can open the file using any suitable browser to see the values, but it's just not necessary. If you are concerned about hacking then encrypt the data in the file - trying to use a different name or a different location won't protect it against hacking.  Data saved as string values can be read by any text editor, and data saved in other forms can be read by any .Net application. If you are concerned about hacking then you need to implement encryption and checksumming.


    • Edited by Acamar Friday, July 22, 2016 10:37 PM sp
    Friday, July 22, 2016 9:51 PM

  • You can change the value of a settings variable in code, but the default is what you specify in the Settings entry.

    What i specify there is not really important, I just need to write that If Setting = "" (or setting file don't exist) Then create new one with [...] -> [...] is the default value.

    Thanks A LOT!!!

    Friday, July 22, 2016 10:33 PM

  •  That seems like a lot of work to duplicate something that has already been built for you.

     That's what happen when I don't understand what they did for me xD

     And I like simple things (one program I am waiting to do when I know enough is something that already exists but it seems for me too complicated so I'm going to make something like that and maybe I understand what it really does).


    Thanks A LOT!!!


    • Edited by Benur21 Friday, July 22, 2016 10:46 PM
    Friday, July 22, 2016 10:35 PM

  • Note that if you change the location then you must ensure it meets the required standards - available on any machine for any version of the OS, specific to the user or the application, specific to the application version, and not protected by security restrictions.  That is not an easy standard to meet.

      I know about that and I am thinking in save data in the same place as the executable (that will be always avaiable) or other place that I see other things using (like where Settings are saved actually).

    Thanks A LOT!!!

    Friday, July 22, 2016 10:37 PM

  •  If you are concerned about hacking then encrypt the data in the file - trying to use a different name or a different location won't protect it against hacking.  Data saved as string values numeric values can be read by any text editor, and data saved in other forms can be read by any .Net application. If you are concerned about hacking then you need to implement encryption and checksumming.

      Then I would need to find what they do to encrypt things... This page does that and I would try to inspect the page html and maybe find what it does: (page in portuguese) https://www.invertexto.com/texto-criptografado

    Thanks A LOT!!!

    Friday, July 22, 2016 10:41 PM
  • What i specify there is not really important, I just need to write that If Setting = "" (or setting file don't exist) Then create new one with [...] -> [...] is the default value.

    You should always nominate a default for every settings variable. However, some, such as Lists, have a complex default value, so it is sometimes simpler to test them for Nothing (not empty) and initialize them to an empty List if they are Nothing.  The settings file will never 'not exist' for your code, because it will have been created by the settings management code by the time that your code starts executing. If you don't know the correct value for the variable until the first time your application runs (for instance, the user enters their name) then you default the settings variable with a value you can recognize, and which is otherwise invalid (such as "" for a string) and that is what triggers the prompt for the user to enter their details.

    Friday, July 22, 2016 10:43 PM

  • If you don't know the correct value for the variable until the first time your application runs (for instance, the user enters their name) then you default the settings variable with a value you can recognize, and which is otherwise invalid (such as "" for a string) and that is what triggers the prompt for the user to enter their details.

    If UserNameSetting = "" Then
    
      UserNameSetting = usernameTextBox.text  ' Or ask for the user name.
    
    End If

    do it needs something more?

      

    Thanks A LOT!!!

    Friday, July 22, 2016 10:55 PM
  • ... I am thinking in save data in the same place as the executable...

    Way WAY bad idea! That's a protected directory Benur. There are better places for it.

    Some people succeed because they were destined to, but most people succeed because they were determined to.

    Friday, July 22, 2016 11:11 PM


  • If UserNameSetting = "" Then
    
      UserNameSetting = usernameTextBox.text  ' Or ask for the user name.
    
    End If

    do it needs something more?

      

    Thanks A LOT!!!

    More like:

    If String.IsNullOrWhiteSpace(My.Settings.UserNameSetting) Then
        ' Code Here
    End If

    *****

    Benur, I'll show you anything you want, but tell me first - what is your compelling reason for not using the built-in Application Settings? Where it saves the data isn't really that important is it?

    It's safe - it's in a good location - why do you want to do it yourself?

    I do for other reasons, but - what is your rationale here?


    Some people succeed because they were destined to, but most people succeed because they were determined to.

    Friday, July 22, 2016 11:18 PM
  • do it needs something more?

    I presume you would want to confirm that the user had actually entered something into the text box.  Although I guess if they hadn't entered anything then it would remain blank and they would get asked again next time.

    Friday, July 22, 2016 11:41 PM
  • Then I would need to find what they do to encrypt things...

    I feel like I'm walking into a play in the middle of Act III here, so I might not be up to speed, but:

    Do you mean string encryption?

    If you're adamant to encrypt it, that's fine and I'll show you how, but there's no reason you can't store the encrypted string in the Application Settings the same as any other string.

    If you mean some other type (maybe a numeric type), so long as there's a .ToString  method that's set up, those can also be used to convert back and forth, and those can be encrypted (as strings) also, as can DateTime instances.

    So I'll ask again: What is your compelling reason to not use Application Settings?

    I'll show you anything you want, but I'm not at all following the logic, honestly.


    Some people succeed because they were destined to, but most people succeed because they were determined to.

    Friday, July 22, 2016 11:49 PM

  • So I'll ask again: What is your compelling reason to not use Application Settings?

      Because I don't understand how it works and why some things are done that way.

      See my last reply/questions on Where Settings are saved.


    Thanks A LOT!!!

    Saturday, July 23, 2016 4:02 PM

  •   Because I don't understand how it works and why some things are done that way.

      See my last reply/questions on Where Settings are saved.


    Thanks A LOT!!!

    That's actually a great reason - I'm serious. I wasn't expecting that.

    *****

    In the properties section, as you've seen, you have a tab for "Settings" and there you can set up a lot of different things. You can add, you can remove if need be - they've done quite a lot to help with that.

    What I'm talking about is nothing at all like it: It's all hard-baked into the code, so a property can't just be added and removed like the fields are in settings.

    So what does happen when it saves then? First, as to the location, Microsoft wrote dotNET and Microsoft wrote the operating system you're using. Who better then they to know a good place to put them. ;-)

    As for what happens when it's saved, it's actually serialized. Please take a few minutes to review this:

    https://msdn.microsoft.com/en-us/library/mt656712.aspx

    Have you ever seen a bunch of ants in line, almost like a little army all walking at the same pace, one after the other? I'm sure you have. You can think about serialization (and the reverse - deserialization) sort of like that but here we're dealing with bytes. One after the other they're "lined up and moving", in this case to a file of a specific format called XML:

    https://msdn.microsoft.com/en-us/library/aa286548.aspx

    XML has good and bad, like anything, but for many things it's good because of the tags. You don't need to worry about position to know what it is, where to find it, or where to extract it back from. It's formatted for just that purpose. But there are caveats.

    Give me ten minutes and I'll continue this - I want to put something together to use as an example.

    Stay tuned. :)


    Some people succeed because they were destined to, but most people succeed because they were determined to.

    Saturday, July 23, 2016 4:19 PM
  • Benur,

    I'm back now and I'll use the following to make my point about XML pros and cons. Let's say that we built a class that has some information about a person:

    Public Class PersonInfo Public Property Name As String Public Property Address As String Public Property DateOfBirth As DateTime Public Property DateOfDeath As Nullable(Of DateTime) End Class

    You might be confused by that last one: A Nullable(Of DateTime).

    One of the most important basic things to understand is the difference between a reference type and a value type. Please do be sure that you take time to fully understand the difference and a starting point on learning that difference is here:

    https://msdn.microsoft.com/en-us/library/t63sy5hs.aspx

    The fact that a DateTime instance is an instance of a structure, it's a value type. A value type has no meaning as "null" - what's a null integer?

    Right! Can't happen (just so you know though, you actually can assign it as "Nothing" and it will accept it but it will just set it to the default which would be 0 for an integer).

    A Nullable(Of T) allows us to "wrap" the actual type in a reference type so that it can be null and that's what the last one is. After all, if the above class was being used for your friends and colleagues, I'm reasonably sure that most in your list wouldn't be dead yet. ;-)

    Well back to why I'm using that as the example, we're talking about XML (what the settings are stored in). XML is structured text. Text - or a string - is a reference type, not a value type, so that presents a problem here if the person is still alive! What would the XML do with a null?

    Do understand that a null string isn't the same as an empty string - far from it.

    Null is nothing; an empty string is just a string which doesn't have any characters in it.

    Before I go further, do know that yes this can be dealt with (several ways) in XML, but I'm trying to make a point that there are drawbacks with anything.

    If you wanted to store data like what's shown in my example little simple class, either set it up so that the result of what's stored in the XML is never null (again, the value type is a DateTime but it's being stored as a string), or forget using XML or any other text file.

    In what I do, mine uses binary serialization and null presents no problem at all.

    *****

    Is any of this helping at all?


    Some people succeed because they were destined to, but most people succeed because they were determined to.

    Saturday, July 23, 2016 4:34 PM
  • Benur,

    I thought I'd put an example together to show you how you might be able to deal with XML when you have a null value. As with anything related to coding, there's never "just one way to do it", and what follows is just one single way - the way that I've come to deal with it.

    All of the code that I'll show should work on your computer - and there's nothing like doing it yourself to see - so if you will please start a new project and in code (there are no controls involved here), replace your code with all of the code below then run it:

    Option Strict On Option Explicit On Option Infer Off Public Class Form1 Private Sub Form1_Load(sender As System.Object, _ e As System.EventArgs) _ Handles MyBase.Load Dim desktop As String = _ My.Computer.FileSystem.SpecialDirectories.Desktop Dim testFilePath As String = _ IO.Path.Combine(desktop, "PersonInfo.xml") ' What you see shown in the code above this is ' that I'm telling VB to put a file on this user's ' desktop. ' ' Even though different operating systems' path to ' the desktop is different, by doing it this way, ' it will always know where to look. ' ' Now I'll create a new person. ' ' We'll assume this guy named 'Frank Smith' is ' still alive for this first example. ;-) Dim pi As New _ PersonInfo("Frank Smith", "Somewhere, USA", #10/20/1958#) Stop ' The "Stop" that you see above works like a ' breakpoint in that code execution will halt when ' it gets to it. When the code halts you can then ' hover your mouse over any variables which are ' then in scope and you'll see that variable's ' value. ' ' When it gets to "Stop" above, hover your mouse ' over the variable "pi" above and have a look ' around at what you'll see. ' ' Now I'll use a method which I put in the class ' called "ExportToXML" and I'll give it the path ' that I created earlier so that it will know ' where to write the new XML file to: pi.ExportToXML(testFilePath) Stop ' At this point, go have a look on your desktop ' and you should see a new file there named ' "PersonInfo.xml. ' ' Open that with a text reader like Notepad and ' have a look (I'll also post a link to it so you ' can see it there). Please take note to how the ' XML looks with "Nothing" as a date of death. pi.ImportFromXML(testFilePath) Stop ' In the code above, I'm using the other method ' that I put in the class named "ImportFromXML" ' which reads the data from the XML file (if it ' doesn't exist it will throw an exception). ' ' Look at the code in that method: My point here ' is that you can see it sets the values of the ' members of the class, so nothing is retained ' from the original declaration of the instance. ' ' Given that, once again hover your mouse over ' "pi" and you should see the data is exactly the ' same as the original instance was. ' ' Now let's kill this guy off ;-)... then we'll ' repeat the process. pi.SetDateOfDeath(#10/22/1958#) Stop ' In the code above, I'm using a method that I put ' in the class that sets the date of death (once ' it's checked the validity of the date). ' ' I'm sure you know what to do now: Hover your ' mouse over "pi" again please. pi.ExportToXML(testFilePath) Stop ' In the code above, I'm going to overwrite your ' existing "PersonInfo.xml" file with the new data ' so when it gets here, once again open that file ' and have a look around please. pi.ImportFromXML(testFilePath) Stop ' Lastly then, I'll import that data back in so ' once it's done, hover your mouse over the ' variable "pi" and you'll see the updated info. ' ============================================ ' Does this help some or did I just muddy the ' water? End Sub Public Class PersonInfo Private _name As String Private _address As String Private _dateOfBirth As DateTime Private _dateOfDeath As Nullable(Of DateTime) Public Sub New(ByVal name As String, _ ByVal address As String, _ ByVal dateOfBirth As DateTime) Try If String.IsNullOrWhiteSpace(name) Then Throw New _ ArgumentException("The name cannot be null or empty.") ElseIf String.IsNullOrWhiteSpace(address) Then Throw New _ ArgumentException("The address cannot be null or empty.") ElseIf address.Contains(vbCrLf) Then Throw New _ ArgumentException("The address cannot contain a line break.") ElseIf dateOfBirth > Now Then Throw New _ ArgumentOutOfRangeException("Date Of Birth", _ "Cannot be in the future!" & vbCrLf) Else _name = name.Trim _address = address.Trim _dateOfBirth = dateOfBirth End If Catch ex As Exception Throw End Try End Sub Public Sub New(ByVal name As String, _ ByVal address As String, _ ByVal dateOfBirth As DateTime, _ ByVal dateOfDeath As DateTime) Try If String.IsNullOrWhiteSpace(name) Then Throw New _ ArgumentException("The name cannot be null or empty.") ElseIf String.IsNullOrWhiteSpace(address) Then Throw New _ ArgumentException("The address cannot be null or empty.") ElseIf address.Contains(vbCrLf) Then Throw New _ ArgumentException("The address cannot contain a line break.") ElseIf dateOfBirth > Now Then Throw New _ ArgumentOutOfRangeException("Date Of Birth", _ "Cannot be in the future!" & vbCrLf) ElseIf dateOfDeath > Now Then Throw New _ ArgumentOutOfRangeException("Date Of Death", _ "Cannot be in the future." & vbCrLf & _ "...or do you have plans?" & vbCrLf) ElseIf dateOfDeath < _dateOfBirth Then Throw New _ ArgumentOutOfRangeException("Date Of Death", _ "Cannot be before they were born!") Else _name = name.Trim _address = address.Trim _dateOfBirth = dateOfBirth _dateOfDeath = dateOfDeath End If Catch ex As Exception Throw End Try End Sub Public Sub SetDateOfDeath(ByVal dateOfDeath As DateTime) Try If dateOfDeath > Now Then Throw New _ ArgumentOutOfRangeException("Date Of Death", _ "Cannot be in the future." & vbCrLf & _ "...or do you have plans?" & vbCrLf) ElseIf dateOfDeath < _dateOfBirth Then Throw New _ ArgumentOutOfRangeException("Date Of Death", _ "Cannot be before they were born!") Else _dateOfDeath = dateOfDeath End If Catch ex As Exception Throw End Try End Sub Public Sub ExportToXML(ByVal filePath As String) Try If String.IsNullOrWhiteSpace(filePath) Then Throw New ArgumentException("The file path cannot be null or empty.") Else Dim fi As New IO.FileInfo(filePath) If Not FolderCanBeWrittenTo(fi.Directory.FullName) Then Throw New _ UnauthorizedAccessException("You do not have permission to write to this directory.") Else Dim xDoc As XElement = _ <PersonInfo> <Data> <Name><%= _name %></Name> <Address><%= _address %></Address> <DateOfBirth><%= _dateOfBirth.Ticks.ToString %></DateOfBirth> <DateOfDeath><%= DateOfDeath_Ticks_String %></DateOfDeath> </Data> </PersonInfo> xDoc.Save(fi.FullName) End If End If Catch ex As Exception Throw End Try End Sub Public Sub ImportFromXML(ByVal filePath As String) Try If String.IsNullOrWhiteSpace(filePath) Then Throw New ArgumentException("The file path cannot be null or empty.") Else Dim fi As New IO.FileInfo(filePath) If Not fi.Exists Then Throw New IO.FileNotFoundException("The file path could not be located.") ElseIf Not fi.Attributes > -1 Then Throw New ArgumentException("The file is corrupt and cannot be read.") Else Dim xDoc As XElement = XElement.Load(fi.FullName) _name = xDoc...<Name>.Value _address = xDoc...<Address>.Value _dateOfBirth = New DateTime(CLng(xDoc...<DateOfBirth>.Value)) Dim dod_TicksString As String = xDoc...<DateOfDeath>.Value If Not String.IsNullOrWhiteSpace(dod_TicksString) Then _dateOfDeath = New DateTime(CLng(dod_TicksString)) Else _dateOfDeath = Nothing End If End If End If Catch ex As Exception Throw End Try End Sub ''' <summary> ''' Gets this person's address. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public ReadOnly Property Address As String Get Return _address End Get End Property ''' <summary> ''' Gets this person's date of birth. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public ReadOnly Property DateOfBirth As DateTime Get Return _dateOfBirth End Get End Property ''' <summary> ''' Gets this person's date of death (if applicable). ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public ReadOnly Property DateOfDeath As Nullable(Of DateTime) Get Return _dateOfDeath End Get End Property ''' <summary> ''' Gets a formatted string showing this person's date of death (if applicable). ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public ReadOnly Property DateOfDeath_Ticks_String As String Get If _dateOfDeath.HasValue Then Return _dateOfDeath.Value.Ticks.ToString Else Return String.Empty End If End Get End Property ''' <summary> ''' Gets this person's name. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public ReadOnly Property Name As String Get Return _name End Get End Property ''' <summary> ''' A method to evaluate whether or not a directory can be written to. ''' </summary> ''' <param name="fldr">The full path of the directory to test.</param> ''' <returns></returns> ''' <remarks></remarks> Private Function FolderCanBeWrittenTo(ByVal fldr As String) As Boolean Dim retVal As Boolean = True Try Dim testPath As String = System.IO.Path.Combine(fldr, "Test.tmp") Dim fi As New IO.FileInfo(testPath) If fi.Exists Then fi.Delete() End If IO.File.WriteAllText(fi.FullName, "") fi.Refresh() retVal = fi.Exists If fi.Exists Then fi.Delete() End If Catch ex As Exception retVal = False End Try Return retVal End Function End Class End Class


    Let me know if that helps at all please?


    Some people succeed because they were destined to, but most people succeed because they were determined to.

    Sunday, July 24, 2016 4:02 PM
  • Benur,

    Well, I managed to mangle that too.

    You need to see the XML on the first write of it, then again on the second write of it, so the following shows that:

    http://www.fls-online.com/VBNet_Forum/07-24-16/PersonInfo_FirstRun.xml

    http://www.fls-online.com/VBNet_Forum/07-24-16/PersonInfo_SecondRun.xml

    ... sorry about that.


    Some people succeed because they were destined to, but most people succeed because they were determined to.

    Sunday, July 24, 2016 4:21 PM

  • So I'll ask again: What is your compelling reason to not use Application Settings?

      Because I don't understand how it works and why some things are done that way.

      See my last reply/questions on Where Settings are saved.


    Thanks A LOT!!!

    Benur,

    I'm wrong!

    At least I think I am. Here's what I'm talking about: Why is it that binary serialization doesn't have a problem with a null?

    It's not that the end result is a binary file, in fact it has nothing to do with that - it's the serialization process. I don't know so, but it's all fitting into place now.

    THAT's why they use serialization (in this case to an XML), rather than writing their own like I did with my example.

    I think I'm right about that.

    Hmm, more to think about but I've learned something here! :)


    Some people succeed because they were destined to, but most people succeed because they were determined to.


    Sunday, July 24, 2016 4:48 PM
  • Why in your first link it says "<DateOfDeath/>" and my first created file in my desktop says

    "<DateOfDeath></DateOfDeath>"? (probably the same thing)


    Thanks A LOT!!!


    • Edited by Benur21 Sunday, July 24, 2016 10:24 PM
    Sunday, July 24, 2016 10:24 PM
  • Why in your first link it says "<DateOfDeath/>" and my first created file in my desktop says

    "<DateOfDeath></DateOfDeath>"? (probably the same thing)


    Thanks A LOT!!!



    Yes, exactly that: It's the same thing, just a different presentation of it is all.

    Some people succeed because they were destined to, but most people succeed because they were determined to.

    Sunday, July 24, 2016 10:30 PM
  • Frank L. Smith,

      Well... I thought the Stop thing really usefull. I don't know so much about Classes because that's the last lesson here and I am still on the tutorial No.40 (I was trying to make my own application updater but I need to save some data to can do that). I was also searching for information about the value types and I am reading about them in order here. XML may have its reasons, specially when it is needed to store data in more than one places (classes, etc). That code is looking simple to me and I will back to it when I want to review some things again.

      Then ok, there's not so much problems with the place where it saves data, or even with the xml organization, but how can I embed that .config file for default values? And for update the application I was thinking on replace the executable with the updated one, letting its data that will be used in the new executable, but if I change its version number then it will make a different path on the Local where it saves values and will not see the already existent data. I also like better only one executable to all the application because then I will not need to zip or rar it if I want to give it to someone via Skype or something. And will not the directory name before the version change too?

      Thanks A LOT for all your help!


    Thanks A LOT!!!

    Monday, July 25, 2016 8:17 PM

  • Hmm, more to think about but I've learned something here! :)

      All that time spent has its costs...

    Thanks A LOT!!!

    Tuesday, July 26, 2016 3:44 PM
  • ... I am thinking in save data in the same place as the executable...


    Way WAY bad idea! That's a protected directory Benur. There are better places for it.

    Some people succeed because they were destined to, but most people succeed because they were determined to.

      Now I want to know more about that protected directories: what directories are protected, what can not be done in protected directories... This new question is here: https://social.msdn.microsoft.com/Forums/vstudio/en-US/98e38ea8-8431-4384-ac03-3e7247e76dba/protected-directories-questions?forum=vbgeneral

    Thanks A LOT!!! ---------END-BENUR21-SIGNATURE----------

    Friday, August 12, 2016 5:50 PM
  • ... I am thinking in save data in the same place as the executable...


    Way WAY bad idea! That's a protected directory Benur. There are better places for it.

    Some people succeed because they were destined to, but most people succeed because they were determined to.

      Now I want to know more about that protected directories: what directories are protected, what can not be done in protected directories... This new question is here: https://social.msdn.microsoft.com/Forums/vstudio/en-US/98e38ea8-8431-4384-ac03-3e7247e76dba/protected-directories-questions?forum=vbgeneral

    Thanks A LOT!!! ---------END-BENUR21-SIGNATURE----------


    Lots are - I don't know of a "list" though.

    Some people succeed because they were destined to, but most people succeed because they were determined to.

    Friday, August 12, 2016 5:59 PM
  • ... I am thinking in save data in the same place as the executable...


    Way WAY bad idea! That's a protected directory Benur. There are better places for it.

    Some people succeed because they were destined to, but most people succeed because they were determined to.

      Now I want to know more about that protected directories: what directories are protected, what can not be done in protected directories... This new question is here: https://social.msdn.microsoft.com/Forums/vstudio/en-US/98e38ea8-8431-4384-ac03-3e7247e76dba/protected-directories-questions?forum=vbgeneral

    Thanks A LOT!!! ---------END-BENUR21-SIGNATURE----------

    Do you know how to read? Is your back sore today so you cant type in a search engine?

    Friday, August 12, 2016 6:23 PM