Showing posts with label General Programming. Show all posts
Showing posts with label General Programming. Show all posts

Monday, February 21, 2011

[2011.02.21] ReSharper C# snippet for MVVM ViewModel Property creation

Here is a simple C# snippet for ReSharper (should work on most versions) to simplify the creation of ViewModel properties. It is clear that creating properties in the ViewModel can be a tedious and repetitive process, especially when there are several involved. To create the snippet, you need to add a new Live Template in R#.

In Visual Studio under the ReSharper menu item, select LiveTemplates... and you will see Fig. 1.

[2011.02.21].ReSharper.snippet.01
Fig.1 The Template Explorer window

Under the User Templates node, select the New Template option from the toolbar and you will be taken to the Template creation page. Here you can enter the shortcut used to toggle the snippet and a description. I used vmp (ViewModel Property) for my shortcut here. Simply copy and paste the code below into the window and I will explain the changes you need to make.

private $TYPE$ _$NAMEFIELD$;

$END$

public $TYPE$ $NAME$

{

    get {return _$NAMEFIELD$; }

    set

    {

        if(_$NAMEFIELD$ == value) return;

        _$NAMEFIELD$ = value;

        OnPropertyChanged("$NAME$");

    }

}

The artifacts enclosed between dollar signs ($) can be thought of as variables that you can replace once the snippet has been activated. If we follow the naming convention of labeling fields starting with an underscore and all properties begin with uppcase letter, you will see that if you leave things the way they are as in Fig. 2, you will not get the anticipated result.

[2011.02.21].ReSharper.snippet.02
Fig.2 Editing the template

This is where the options in the right pane of the Template window comes into play. There are built in macros to help us get the correct set up. We want the $NAME$ to basically be like $_NAMEFIELD$ but without the underscore and the first letter must be upper case. So click the "Choose macro" option next to the NAME identifier in the right pane and from the list, as in Fig. 3, select:
Value of another variable with the first character in upper case

[2011.02.21].ReSharper.snippet.03
Fig.3 Macro selection

After that, the Template window will look like Fig. 4. Note that we have not yet based the $NAME$ on the $_NAMEFIELD$ variable yet.

[2011.02.21].ReSharper.snippet.04
Fig.4 After setting the macro

Now click the another variable link and you will get a dropdown list to select which variable $NAME$ should use as its basis. This is shown in Fig. 5.

[2011.02.21].ReSharper.snippet.05
Fig.5 Relating variables

Your snippet is now ready for action!

NOTE: OnPropertyChanged should be replaced by whatever method name you used when you implemented INotifyPropertyChanged. For instance, you may have called yours RaisePropertyChanged instead of OnPropertyChanged, so modify the snippet to best suit your needs.

Friday, November 20, 2009

[2009.11.20] How to Download PDC2009 Videos using Firefox and DownThemAll!

This is a quick little post on how to download all the PDC 2009 videos in one go (well almost) with Firefox.

All you need is the DownThemAll! extension for Firefox and you are good to go. In case the link changes in the future just search for it on Mozilla's website.

Steps:

  • Install DownThemAll!
  • Go to the videos section on the PDC2009 main page
  • Right click and select DownThemAll! from the context menu as in Fig. 1.
[2009.11.20].01.PDC2009  
Fig. 1
  • Set the location of the downloaded files (1) and add a filter (2) for the types of files you want to get. In this case, I wanted the high definition versions of the videos, but all the videos end with .wmv. The hi-def files are in the wmvhigh folder so by using that as the filter, I can only grab the ones I wanted. You can also change the filter to get the pptx files as well. This is in Fig. 2.
    NOTE: Make sure you have a few gigs of hard drive space and time, because it will take a while to get them all.
[2009.11.20].02.PDC2009
Fig. 2
  • Once the download starts (you can change the number of simultaneous downloadable files) you will see something like Fig. 3. Don't worry about the incompletes or failed files, you can always go back and resume getting them. Notice also that the files are named in the format of CL00.wmv and FT00.wmv. The PDC website has a renamer batch file you can download to change the names of the files once they are downloaded. [Get the file and instructions]
[2009.11.20].03.PDC2009  
Fig. 3

Sunday, November 1, 2009

[2009.11.01] I spent a Week in PRISM

I had heard of Prism a while ago but never really investigated. When I did take a look at it about a month ago, in all honesty I felt overwhelmed. However, recently I had two interesting conversations and that prompted me to sit down and really get into Prism. I am glad I did as I have learned so much and it has shown me how much more I need to learn as well.

I suppose I am more of a code monkey rather than an architect or a designer. That will change from now on. There is no point in me banging out code when I am only aware of part of the system I am writing for. Going through the Prism docs touches on a lot of concepts that I was not familiar with in the first place. All in all, I know I can't get it all in one reading of the doc, but it's a start. I am much more comfortable with terms like Inversion of Control, Dependency Injection, Delegate Commands (well I got this from learning about Model-View-ViewModel), Event Aggregator, Modules, Bootstrapper, and some Design Patterns. Thus far, all I have done is the basic Hello World in Prism but I hope to do more in the near future. I would like to reference some additional resources that in my opinion, will supplement learning not just Prism, but design and architecture in general.

Prism Related

Supplemental Information

Monday, June 29, 2009

[2009.06.29] Visual Studio: AccessViolationException and BitDefender

I recently ran into an error that was annoying so I think it is worth its own post. Basically, I started getting a AccessViolationException error when I tried to run my code in Debug Mode and could not figure out what was going on. Even with a brand new Console Application I was getting the error.

It turns out the culprit was BitDefender. The previous night I was screwing around with Visual Studio and somehow moving tabs around caused BD to think that VS was executing malicious code. A warning popped up and instead of reading it (doh!), I just clicked it away. The next day my headaches started. Basically, Visual Studio was added to the Behavioral Scanner list under the Anitvirus tab.

So if you are running Visual Studio and BitDefender and you start getting the AccessViolationException error, delete the Visual Studio entry from the Behavioral Scanner list and you should be just fine. I would assume that this may apply for other antivirus software out there.

Update:[2009-06-30] I do not think this is just a BitDefender error as I have run into it again and it seems to be just a Visual Studio 2010 Beta 1 error. I am in the middle of a project that refuses to debug at all. XAML IntelliSense is non functioning as well. But VS2008 seems fine so far. This is really annoying!

Update 2: [2009-07-01] One thing I didn't mention earlier is that I reformatted and reinstalled Windows Server 2008 x64, but now with SP2. The thing is that I had both VS2008 SP1 and VS2010 B1 running side by side in with SP1 and the exact same version of Bitdefender, and I had no problems at all. Now I am not even sure if the AccessViolationException is a SP2 issue or not. For now, I turned off vshost.exe in both versions of VS and now I can debug. In the Solution Explorer, right click the name of the project you are using, select Properties, select the Debug tab, and scroll down and uncheck the Enable the Visual Studio Hosting Process. As soon as I do this, everything works.

Thursday, November 20, 2008

[2008.11.20] Fun with Windows Server 2008

I have used Windows XP 64 / Server 2003 for a few months and I liked it a lot. Having upgraded my laptop, I decided to try Windows Server 2008 64-bit Enterprise Version. I am currently running this on an Acer Aspire 5110: AMD Turion X2 1.6GHz, AMD ATI X1600 Video Card, 4GB RAM and a 500GB WD hard drive. Upgrading my RAM to 4GB and HS from 160 to 500GB plus the fact that there is a cool tool to convert Windows Server 2008 to a workstation was motivation enough for me.

You can download the image of Windows Server 2008 from Microsoft and try it for 60 days. The installation was actually a lot faster than installing XP. After using the tool to do the conversions, everything seemed to work fine. While Server 2008 is thus far excellent and comes with a lot of generic drivers (this is both good and bad), there were a few devices that were not installed automatically.

We have, at some point all seen that annoying little yellow icon saying Windows have no idea what that device is, nor is Windows Update any help. Without knowing what the device is, you really can't address the problem.

[2008.11.14].windows.device.manager
Fig.1 Famous Unknown Devices

However, there are tools to help out. Two that I have used to get detailed information on my system are Lavalys Everest and HWiNFO32.

[2008.11.14].everest.device.manager
Fig.2 Using Everest to get more info on devices

Installing drivers for unknown devices is easy, it is upgrading drivers to the latest version seem to be an issue as we shall soon see.

Issues I have with Server 2008: Some fixed, Some not

[1] Blue Screen of Death (BSOD) in Windows Server 2008 + Manual Driver Install [ fixed (so far) ]

It took me a while to install and configure everything to my preferences and I thought that was that. However, I started getting Blue Screen of Death (BSOD) every so often. However, the feedback you get after rebooting gives you enough information to address the problem. From the report, it indicated that the problem was caused by a Realtek device and a simple search yielded that this device was actually the onboard hi-def sound card.

[2008.11.13].bd_error
Fig.3 Report after BSOD

I figured updating the drivers for the Realtek 8110/8169 series would take care of this mess, but doing so was not as simple as it should be. I checked the version of the audio drivers and saw they were from 2006 and it was a generic Microsoft one. Even Windows Update did not try to get the updated drivers from the device makers.

Updating drivers was a cinch in XP but here it was not. When updating drivers, I like to do just that, get the driver package and manually point the driver update for the device to the folder with the drivers. However, when I tried to do that I kept getting the same message over and over - that the 2006 generic drivers were the most current. For instance, this is what Windows said when I tried to update the LAN drivers.

[2008.11.14].lan.default.driver.1
Fig.4 Windows says 2006 LAN drivers most current

Every time I uninstalled the device and rebooted, Windows automatically installed the generic drivers. Even though I disabled this behavior, it still did this, so I am not sure if this is a bug or what.

[2008.11.14].change.driver.install.1
[2008.11.14].change.driver.install.2
Fig.5 Changing how Windows will install drivers

This did not work.

The only way to I found to make Windows Server update drivers is to download a full install package (msi/exe) and let the installer "force" the driver update. I personally do not like doing this which is why it wasn't my first instinct, as I find that some of these installer packages often put supplemental programs that I could care less about.

Even after I did this, I still kept on getting BSOD. At first, based on the Windows report, I thought that listening to music and using the internet at the same time was the problem. So usually, I turn my music off before going online. However, I was still getting BSODs, even when I was copying data between partitions on my external drive. It led me to conclude that the problem is with the network drivers instead, which happen to be from Realtek as well.

Again, note that the network drivers installed were from 2006 and Windows was not letting me do driver update the way I wanted to.

[2008.11.14].lan.default.driver.2
Fig.6 LAN drivers are old

Again, I used an installer package from Realtek and updated the LAN drivers. However, Windows was still not using my updated Realtek device as the default NIC. Instead, it was uing some sort of virtual device that was still using the old drivers and as such, I was still getting BSODs. So I diabled the virtual device and made the Realtek NIC my default device.

[2008.11.14].lan.default.driver.3
Fig.7 Disable virtual NIC

So far, I have listened to music and worked online simultaneously and have not had BSOD yet. Hope this solves the problem.

[2] Peer Guardian 2 [ fixed ]

Again, given that it worked on XP64, I didn't think that I would have any issues with this. So I started off by installing the regular 64-bit version (Peer Guardian 2.0 Beta 6b [pg2-x64.exe] ) and that installed perfectly fine, but for some reason it was blocking, then not blocking.

So reading around, I came across PeerGuardian 2 RC1 Test which again installed flawlessly, but again, there were some issues.

The first problem is actually trying to load/start PG2. I kept getting the error:

[2008.11.13].pg_error
Fig.8 Peer Guardian start error

This is due to some sort of digital signing driver and you can turn this off when you boot into Server 2008. Hit F8 and choose the Disable Driver Signature Enforcement option. This error will go away and you can run PG2.

Note1: I always boot in this mode.
Note2: This can actually be the first thing you do or you can install PG first, but when you start PG, you will get a driver access type error and you would have to reboot and do this step. Actually, you have to do this each time you reboot.

The second problem is that there were times when it seems to work, then not work and I could not figure out exactly what is going on. At first I thought it was because I modified my hosts file to the one from MVP.org and even though I kept switching between my original and modified hosts, the problem continued. As well as the lists that come with PG, I use the Blocklist Manager software from Bluetack Internet Security Solutions to get other compatible block lists as well, such as for torrents. I used to run their ProtoWall software with PG under XP32 but I could never get it working on XP64 and I haven't bothered with Server 2008.

To get Peer Guardian 2 to work on Server 2008:

  1. Install PeerGuardian 2 RC1 Test.
  2. Reboot and keep hitting F8, then select the option Disable Driver Signature Enforcement
  3. After install, update the lists
  4. If for some reason it does not look like it's working (i.e. not blocking), then click the Disable button on PG's main window, hit Check Updates and when it is done, Enable it once more. So far this has worked for me. Other suggestions I came across said to quite PG, and delete the files: cache.p2b, history.db and pg2.conf
[3] Hyper-V and Visual Studio 2010 CTP [ not fixed ]

There is a great guide on how to get the VM image of VS2010 to work on Server 2008. It does not work for me as I keep getting the hypervisor error shown in the image.

[2008.11.13].vs2010_error
Fig.9 Hyper-V + VS2010 Error

As far as I can tell, my CPU supports virtualization.

[2008.11.13].processor_test
Fig.10 Processor Test
So far, I have not found a solution to this and I have installed Virtual PC to work with VS2010.

It seems that even though my CPU is capable, it is not turned on automatically. My BIOS has no option for doing that. As of Nov. 20 2008, Acer has not issued a BIOS fix to address this problem. Given the rate that they update stuff, I don't plan on holding my breath.

Monday, July 7, 2008

[2008.07.07] Copy Visual Studio Code to Blog

It took me a little while to get my blog off the ground because I could not get it to look how I wanted it - namely in terms of code formatting. I looked for a universal solution but soon realized that there was none, at least not for me. So I experimented and yelled at my computer a few times and I will now outline the fruits of my labor.

As far as I can tell, you cannot use custom CSS with your blog posts (Google Blog) at least. I tried to modify the underlying template by adding a set of CSS rules but when I uploaded a post, the rules are never applied. Modifying the template changes the default look of the blog basically. The best way to get your look is to use Inline Styles. It takes a little effort to start, but it is worth it and I will add the items I use here so perhaps it will not be as hard as afterall!
Primarily I use three tools: I only use LW to verify the look I want and to publish the post. I do all my major editing in MS Web. Obviously, you can use any HTML editor you want but MS Web has built in IntelliSense so crunching out the inline styles are especially quick and easy. In addition, there are a few other plugins for LW that allows you to copy formatted code, but I simply do not like the end result of those plugins. Again, it is up to your tastes and Brig Lamoreaux has a review on some of these.

The star of the show is the CopySourceAsHTML plugin for Visual Studio. There is not VS2008 version of this plugin, however, it will still work. I recommend looking at how to get and install the plugin either from Guy Burstein or Andreas Erben blog posts.

The plugin is great for blocks of code, but if you have language specific keywords scattered all across your post and you want to format them as well then inline styles is here to save the day. That's it, there is no other way I can think of right now. So what I do is make a text file with a few tags that I know I will frequently use and when it is time to do so, all I have to do is copy and paste.

For example, in my blog, I use an outer <div> tag to wrap all the contents of that particular post and it looks like:

<div style="font-family: Tahoma;

    font-size: medium;

     padding: 2px;margin: 2px;

     width: 460px;

     text-align: justify;"> <!-- START outer div-->

<!-- Contents of Post goes here -->

</div><!-- END outer div -->


To get the code look such as System.Collections use:

<span style="color:#000000; font-family:'Courier New', Courier, monospace"></span>


To get the color used for classes in C#, use:

<span style="color:#2C92AF; font-family:'Courier New', Courier, monospace"></span>


For example, to get System.Console do something like:

<span style="color:#000000; font-family:'Courier New', Courier, monospace">System.</span>

<span style="color:#2C92AF; font-family:'Courier New', Courier, monospace">Console</span>


Looking at my previous posts, you can see the effect that CopySourceAsHTML and inline style sheets has on the overall look of the blog. As I said, it is a bit of a pain to use the inline styles, and I doubt everyone will have the patience to do it this way. Hope this helps, feel free to ask any questions if needed.

Friday, February 1, 2008

[2008.02.01] Object Oriented Programming

I figured as my first blog post, I should start off with the basics and work my way up.

Object Oriented Programming (OOP) is basically a method of using real world objects (table, dog, car) as a basis of designing and writing applications, i.e. write applications that take on the characteristics of everyday objects/items we are used to interacting with.

When you think of an object, you imagine that it is something real, tangible and it is something you can interact with. As such, when you are writing code that reflects objects, you want the code to 'feel' as though you are actually interacting with the actual object you are trying to model.

For instance, take a look at a person as an object. As an object and a person it will have certain characteristics or properties such as height, weight, eye color. Also, the person can also be in a certain state, such healthy, sick, bored, playful, etc. Finally, the person may exhibit certain actions or behaviors such as walking, talking and in general 'doing something'.

These three items - property, state and behavior is the basis of building an object in code.

In order for an application to be considered 'object oriented', it must follow the ideals of the Pillars of Objected Oriented Programming. These are:

[1] Encapsulation

[2] Inheritance

[3] Polymorphism

Thursday, November 1, 2007

[2007.11.01] Fast Fourier Transform (FFT/IFFT) in C#

Outlined here is my implementation of the Fast Fourier Transform (FFT) and the Inverse Fast Fourier Transform (IFFT) in C#. The FFT/IFFT classes accepts and return an array of Complex values to be transformed. In addition, helper methods within the classes do the grunt work of padding the array with zeros and performing the actual computations to return a valid FFT/IFFT object. As you can see from the code file, this is well documented and detailed so that anyone can follow and reproduce what I have done.

In addition, I have compared the results I received after running my test program to a similar setup in Matlab and my results were verified in both cases. The class diagram below illustrates the features of the FFT class.

[2007.11.01].fft
Fig.1 Class diagrams for FFT/IFFT

 /********************************************

*  Author Name : Surujlal 'Sparky' Dasrath  *

*  Date        : November 01 2007           * 

*  Contact    : sdasrath@gmail.com        *

* *******************************************

*/

using System;

using System.Collections.Generic;

using System.Drawing;

using System.Linq;

using System.Text;

 

namespace FastFourier

{

    #region Summary of FFT and IFFT

    /*  Verion: 1.0.0

    *  Member List:

    *      [1] TYPES

    *          -> FFT

    *          -> IFFT

    *          -> FourierTransformException

    *      [2] PRIVATE FIELDS

    *          FFT:

    *              -> complexArrayInput - an array of Complex types

    *              -> noOfPoints - number of points to be used in the FFT calculation

    *              -> modifiedArray - an arry of Complex type that is a resized version of complexArrayInput

    *          IFFT:

    *              -> complexArrayInput - an array of Complex types

    *              -> noOfPoints - number of points to be used in the IFFT calculation

    *      [3] ACCESSOR METHODS/ PROPERTIES

    *          FFT:

    *              -> ComplexArray - read/write property that accesses the complexArrayInput field

    *              -> NumberOfPoints - read/write property that accesses the noOfPoints field

    *              -> ModifiedArray - read/write property that accesses the modifiedArray field

    *              -> Length - gets the length of an array

    *      [4] CONSTRUCTORS

    *              -> FFT(Complex[] complexArray) - initialize an instance of the FFT type using its argument

    *                  to set the complexInputArray field

    *              -> FFT(Complex[] complexArray, Int32 noOfPoints) - initialize an instance of the FFT type using

    *                  the first argument to set the complexInputArray field and the second to set numberOfPoints

    *              -> IFFT(Complex[] complexArray) : base(complexArray) - inherits from FFT and used to

    *                  initialize an instance of the FFT type using its argument to set the complexInputArray field

    *              -> IFFT(Complex[] complexArray, Int32 noOfPoints) : base(complexArray, noOfPoints) - inherits

    *                  from FFT and is used to initialize an instance of the FFT type using the first argument

    *                  to set the complexInputArray field and the second to set numberOfPoints

    *      [5] METHODS

    *              -> Fft() - used to call ZeroPad() and DoFFT() methods

    *              -> ZeroPad() - truncate/extend-by-zero-padding/leave-intact a Complex array

    *              -> DoFFT() - perform Fourier decomposition

    *              -> Real(Complex[] x) - returns real part of each element of an array of Complex types

    *              -> Imaginary(Complex[] x) - returns imaginary part of each element of an array of Complex types

    *              -> Abs(Complex[] x) - returns the magnitude of each element of an array of Complex types

    *              -> Equals() - overridden method of System.Object to suit the needs to FFT/IFFT

    *              -> GetHashCode() - overridden method of System.Object to suit the needs of FFT/IFFT

    * */

    #endregion

 

    #region Start of Class "FFT"

 

    //        N

    // X(k) = SUM x(n) * Exp(-j * 2 * PI * k * n / N)       1 <= k <= N

    //        n=0

    // and Euler's Identity:

    //       j*theta

    //      e        = cos(theta) + j * sin(theta)

 

    /// <summary>

    /// Performs the Fast Fourier Transformation technique on an array of real or complex values

    /// and returns the result.

    /// </summary>

    public class FFT

    {   // start definition of Class fft01

 

        #region FFT -> PRIVATE FIELDS

        /// <summary>

        /// Array of time domain Complex values to be transformed to frequency domain using FFT.

        /// </summary>

        private Complex[] complexInputArray;    // x(n)

 

        /// <summary>

        /// 32-bit representation of the number of points used in the FFT calculation.

        /// </summary>

        private Int32 noOfPoints;               // N

 

        /// <summary>

        /// Modified array of time domain Complex values to be transformed to frequency domain using FFT.

        /// Modification is in the form of either no changes was done to the original input array or the input

        /// was truncated/zero-padded.

        /// </summary>

        private Complex[] modifiedArray;          // x(n) - Modified for FFT

        #endregion

 

        #region FFT -> ACCESSOR METHODS/PROPERTIES

        /// <summary>

        /// Gets or sets the array to be transformed.

        /// </summary>

        public Complex[] ComplexArray

        {// start property "ComplexArray"

            get // gets x(n)

            { return this.complexInputArray; }

            set // sets x(n)

            { this.complexInputArray = value; }

        }// end property "ComplexArray"

 

        /// <summary>

        /// Gets or sets the number of points used in the Fast Fourier transformation.

        /// </summary>

        public Int32 NumberOfPoints

        {// start property "NumberOfPoints"

            get // gets N

            { return this.noOfPoints; }

            set // sets N

            { this.noOfPoints = value; }

        }// end property "NumberOfPoints"

 

        /// <summary>

        /// Gets or sets the number of values in the array with respect to the number of FFT points.

        /// </summary>

        public Complex[] ModifiedArray

        {// start property "ModifiedArray"

            get

            { return this.modifiedArray; }

            set

            { this.modifiedArray = value; }

        }// end property "ModifiedArray"

 

        /// <summary>

        /// Gets the length of the input array to be transformed.

        /// </summary>

        public Int32 Length

        {// start property "Length"

            get

            { return this.complexInputArray.Length; }

        }// end property "Length"

        #endregion

 

        #region FFT -> CONSTRUCTORS

        /// <summary>

        /// Initialize an new instance of a FFT object using the "complexArray" argument

        /// to populate the array to be transformed.

        /// </summary>

        /// <param name="complexArray">An array of Complex types to be transformed.</param>

        public FFT(Complex[] complexArray)

        { // start "FFT(Complex[] complexArray)"

            this.complexInputArray = complexArray;

            this.noOfPoints = complexArray.Length;

            this.modifiedArray = new Complex[this.noOfPoints];

        } // end "FFT(Complex[] complexArray)"

 

        /// <summary>

        /// Initialize an new instance of a FFT object using the "complexArray" argument

        /// to populate the array to be transformed and the "noOfPoints" argument to set

        /// the number of points used in the calculation.

        /// </summary>

        /// <param name="complexArray">An array of Complex types to be transformed.</param>

        /// <param name="noOfPoints">32-bit representation of the number of FFT points to be used.</param>

        public FFT(Complex[] complexArray, Int32 noOfPoints)

        { // start "FFT(Complex[] complexArray, Int32 noOfPoints)"

 

            try

            {

                this.complexInputArray = complexArray;

                this.noOfPoints = noOfPoints;

                this.modifiedArray = new Complex[this.noOfPoints];

 

                if (noOfPoints <= 0)

                    throw new FourierTransformException("The number of points must be greater than 0");

            }

            catch (FourierTransformException ex)

            {

                Console.WriteLine(ex.Message.ToString());   

            }

        } // end "FFT(Complex[] complexArray, Int32 noOfPoints)"

        #endregion  // End region definition for Constructors

 

        #region FFT -> METHODS

        /// <summary>

        /// Performs a complete Fast Fourier Transformation on an array of Complex values.

        /// Automatically calls ZeroPad() to leave/truncate/pad-with-zeros the array as

        /// specified by the number of FFT points to be used; then calls the DoFFT() method

        /// which is where the actual FFT computations are done.

        /// </summary>

        /// <returns>Returns an array of Fourier Transformed values.</returns>

        public Complex[] Fft()

        {   // start method "Complex[] Fft()"

 

            // First:

            // call the ZeroPad() method and that will retrieve the original

            //  input array of values to be transformed; ZeroPad() will also

            //  resize the array appropriately to the number of FFT points

            //  desired in the output before any processing is done

            Complex[] modArr = ZeroPad();

 

            // Second:

            // call the DoFFT() method which is where all the processing/math is done

            Complex[] freqDom = DoFFT();

 

            // return the results to the caller

            return freqDom;

        }   // end method "Complex[] Fft()"

 

        /// <summary>

        /// Used to either leave the original input array intact or truncate or

        /// zero pad the array based on the number of FFT points to be used. It is

        /// called from within DoFFT() and handles conditions where the Number of FFT points

        /// is equal, less than and greater than the length of the input array.

        /// </summary>

        /// <param name="inputArray">The array of Complex values that will undergo FFT.</param>

        /// <returns>Returns a new Complex valued array that has the same number of indices

        /// as the number of FFT points.

        /// <list type="bullet">

        /// <item>If the number of FFT points EQUALS the length of the input array,

        /// nothing needs to be done and the original input array is returned.</item>

        /// <item>If the number of FFT points is LESS than the length of the input array,

        /// then the result array is truncated up to the 'FFT points' index.</item>

        /// <item>If the number of FFT points is GREATER than the length of the input array,

        /// then the length of the resultant array will be based on the number of FFT points

        /// and each additional index is filled with zero valued Complex objects.</item>

        /// </list>

        /// If the number of FFT points is less than the length

        /// of the </returns>

        /// <remarks>This method is provided in order to provide users with a finer

        /// grain of control at each step of the calculations.</remarks>

        public Complex[] ZeroPad()

        {// start method "public Complex[] ZeroPad(Complex[] inputArray)"

 

            // This method will test 3 conditions and the resulting output

            //  array is based as each of these are evaluated

            //  [1] If the number of FFT points and the input array

            //      that is to have FFT performed on it has an EQUAL

            //      number of points, then just return the original

            //      input array

            //  [2] If the number of FFT points is GREATER than than the

            //      size of the input array, create a new array and copy

            //      over all the results of the input array and the

            //      remaining indices are to be filled with zero-valued

            //      Complex objects

            //  [3] If the number of FFT points is LESS than the size

            //      of the input array then copy over that many points

            //      to the new array of Complex values and discard the rest

 

            // [1] Perform Step 1: if FFT points EQUAL length of input array

            //      do nothing and just return the input array without modification

 

            // First:

            // retrieve the original user input array of values stored in the

            //  properties of the type

            Complex[] inputArray = this.ComplexArray;

 

            // [1] Perform Step 1

            if (inputArray.Length == this.noOfPoints)

            {

                this.modifiedArray = inputArray;

                return inputArray;

            }

 

            // [2,3] Perform Steps 2 & 3:

            else

            {

                // create an array that will hold Complex objects and make

                //  the length of the array as large as the number of points

                //  that the FFT formula uses; in this case the number of

                //  FFT points is GREATHER than the length of the input array

                Complex[] paddedArray = new Complex[this.NumberOfPoints];

 

 

                // iterate through the newly created array (paddedArray)

                //  and at each index, create a new Complex object

                //  with both the real and imaginary fields set to 0

                for (Int32 i = 0; i < this.NumberOfPoints; i++)

                {// start for with i=0

 

                    // create Complex objects with real & imaginary

                    //  fields set to 0

                    paddedArray[i] = new Complex(0, 0);

 

                    // within the same for loop and at matching indices,

                    //  copy the value of the original input array to the

                    //  newly created padded array

                    //  NOTE: The 'if' does step 3, the 'else' does step 2

                    if (i < inputArray.Length)

                    { // start if

                        paddedArray[i] = inputArray[i];

                    } // end if

                    else

                    { // start else

                        // since the original array is smaller than

                        //  the new padded one, no value need to be

                        //  copied over, BUT the resulting indices still

                        //  need to be zeroed out; jump out of the if-else

                        //  conditions and continue processing the for loop

                        //  which will contine to zero out the remaining indices

                        continue;

                    } //end else     

                }// end for with i=0

 

                // return the new zero padded array after all processing is done

                this.modifiedArray = paddedArray;

                return paddedArray;

            }

        }// end method "public Complex[] ZeroPad(Complex[] inputArray)"

 

        /// <summary>

        /// The actual FFT computations are done within this method.

        /// </summary>

        /// <returns>Returns an array of Complex values that have been transformed

        /// using the Fourier Transformation technique.</returns>

        /// <remarks>This method is provided in order to provide users with a finer

        /// grain of control at each step of the calculations.</remarks>

        public Complex[] DoFFT()

        {// start method "public Complex[] DoFFT(Complex[] paddedArray)"

            //        N

            // X(k) = SUM x(n) * Exp(-j * 2 * PI * k * n / N)

            //        n=0

            // and Euler's Identity:

            //       j*theta

            //      e        = cos(theta) + j * sin(theta)

            // the resulting array will hold the computations after

            //  FFT is performed and it will be the same length

            //  as the number of FFT points (same as the lenth

            //  of the padded array from the ZeroPad() method)

            //  result = X(k);  paddedArray = x(n)

 

            // retrieve the modified input array from the property

            Complex[] paddedArray = this.ModifiedArray;

 

            // create storage for the resulting transformed output

            Complex[] frequencyDomain = new Complex[paddedArray.Length];

 

            // get the number of FFT points based on the length of

            //  the padded array; this is done to simply shorten

            //  some of the expressions below

            Int32 points = paddedArray.Length;

 

            // outer iteration to determine the value of each point

            //  in the result set of the FFT transformation

            //  this loop calculates the X(k)'s in the FFT equation

            for (Int32 k = 0; k < points; k++)

            { // start for with k=0

 

                // temp1 will hold the results of the inner interations

                //  below and it is reset on each outer iteration

                Complex temp1 = new Complex(0, 0);

 

                // inner iteration to compute the sums of values needed

                //  for each FFT point - this is a shifted sum of x(n)'s

                for (Int32 n = 0; n < points; n++)

                { // start for with n=0

 

                    // local variable to compute each iteration of

                    //  x(n) * exp(...)

                    Complex temp2 = new Complex(0, 0);

 

                    // local variables to hold the result of each

                    //  part of the Euler Identity portion of the

                    //  FFT transformaton equation

                    Double real_part = 0;   // cos(theta)

                    Double imag_part = 0;   // sin(theta)

 

                    real_part = Math.Cos((2 * Math.PI * n * k) / points);

                    imag_part = Math.Sin((2 * Math.PI * n * k) / points) * -1;

 

                    temp2.Real = real_part;    // set the Real and Imaginary properties of the local

                    temp2.Imaginary = imag_part;//  Complex object uses to keep track of computations

 

                    // X(k) = [cos(T) + j Sin(T)] * x(n)

                    temp2 = temp2 * paddedArray[n];

                    temp1 = temp1 + temp2;  // sum each successive iteration

                }//end for with n=0

 

                // pass each calculated FFT point back to the result array

                frequencyDomain[k] = temp1;

            } // end for with k=0

 

            return frequencyDomain;

        }// end method "public Complex[] DoFFT(Complex[] paddedArray)"

 

        /// <summary>

        /// Retrieves the real part of each Complex value in an array of Complex objects.

        /// </summary>

        /// <param name="complexArray">An array of Complex types.</param>

        /// <returns>Returns an array of Double values representing the real part of each Complex value.</returns>

        public Double[] Real(Complex[] complexArray)

        {// start method "public Double[] Real()"

            try

            {

                if (complexArray == null)

                { throw new NullReferenceException("Object is a null reference and needs to be initialized"); }

                else

                {

                    Double[] real = new Double[complexArray.Length];

 

                    for (Int32 i = 0; i < complexArray.Length; i++)

                    {// start for with i=0

                        real[i] = complexArray[i].Real;

                    }// end for with i=0

                    return real;

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine("Error: " + ex.Message);

                throw;

            }

 

        }// end start method "public Double[] Real()"

 

        /// <summary>

        /// Retrieves the imaginary part of each Complex value in an array of Complex objects.

        /// </summary>

        /// <param name="complexArray">An array of Complex types.</param>

        /// <returns>Returns an array of Double values representing the imaginary part of each Complex value.</returns>

        public Double[] Imaginary(Complex[] complexArray)

        {// start method "public Double[] Imaginary(Complex[] complexArray)"

            try

            {

                if (complexArray == null)

                { throw new NullReferenceException("Object is a null reference and needs to be initialized"); }

                else

                {

                    Double[] imag = new Double[complexArray.Length];

                    for (Int32 i = 0; i < complexArray.Length; i++)

                    {// start for with i=0

                        imag[i] = complexArray[i].Imaginary;

                    }// end for with i=0

                    return imag;

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine("Error: " + ex.Message);

                throw;

            }

        }// end method "public Double[] Imaginary(Complex[] complexArray)"

 

        /// <summary>

        /// Computes the absolute value/magnitude of a Complex object.

        /// </summary>

        /// <param name="complexArray">An array of Complex types.</param>

        /// <returns>Returns an array of Double values representing the absolute value/magnitude of each

        /// index of the complexArray argument.</returns>

        public Double[] Abs(Complex[] complexArray)

        {// start method "public Double Abs(Complex[] complexArray)"

            try

            {

                if (complexArray == null)

                { throw new NullReferenceException("Object is a null reference and needs to be initialized"); }

                else

                {

                    Double[] abs = new Double[complexArray.Length];

 

                    for (Int32 i = 0; i < complexArray.Length; i++)

                    {// start for with i=0

                        //abs[i] = Math.Sqrt((complexArray[i].Real * complexArray[i].Real) + (complexArray[i].Imaginary * complexArray[i].Imaginary));

                        abs[i] = complexArray[i].Modulus();

                    }// end for with i=0

                    return abs;

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine("Error: " + ex.Message);

                throw;

            }

        }// end method "public Double Abs(Complex[] complexArray)"

 

        /// <summary>

        /// Overriden version of the System.Object.Equals() method.

        /// </summary>

        /// <param name="obj">Object type to be compared to.</param>

        /// <returns>Returns true if the current object and the argument 'obj' are equal and false otherwise.</returns>

        public override Boolean Equals(Object obj)

        {

            if (obj == null)

                return false;

            if (obj is FFT)

            { return this == (FFT)obj; }

            else

            { return false; }

        }

 

        /// <summary>

        /// Overidden version of System.Object.GetHashCode() method.

        /// </summary>

        /// <returns>A hash code for the current FFT object.</returns>

        public override Int32 GetHashCode()

        {

            return base.GetHashCode();

        }

        #endregion // End region defintion for Methods

 

    }// end defintion of Class "FFT"

    #endregion // End region definition for Class "FFT"

 

    #region Start Class "IFFT"

    //        1    N

    // x(n) = - * SUM X(k) * Exp(j * 2 * PI * k * n / N)        1 <= n <= N

    //        N   n=0

    // and Euler's Identity:

    //       j*theta

    //      e        = cos(theta) + j * sin(theta)

    //

    /// <summary>

    /// Performs the Inverse Fast Fourier Transformation on an array of real or complex values

    /// and returns the result.

    /// </summary>

    public class IFFT : FFT

    {// start of class "IFFT"

 

        #region IFFT -> PRIVATE FIELDS

        /// <summary>

        /// Array of frequency domain Complex values to be transformed to time domain using IFFT.

        /// </summary>

        private Complex[] inputArray;

 

        /// <summary>

        /// 32-bit representation of the number of points used in the IFFT calculation.

        /// </summary>

        private Int32 noOfPoints;

 

        /// <summary>

        /// Modified array of frequence domain Complex values to be transformed to time domain using IFFT.

        /// Modification is in the form of either no changes was done to the original input array or the input

        /// was truncated/zero-padded.

        /// </summary>

        private Complex[] modifiedArray;

        #endregion  // End of region definition for Private Fields

 

        #region IFFT -> ACCESSOR METHODS/PROPERTIES

 

        /// <summary>

        /// Gets or sets the array to be transformed.

        /// </summary>

        public new Complex[] ComplexArray

        {// start property "ComplexArray"

            get

            { return this.inputArray; }

            set

            { this.inputArray = value; }

        }// end property "ComplexArray"

 

        /// <summary>

        /// Gets or sets the number of points used in the Fast Fourier transformation.

        /// </summary>

        public new Int32 NumberOfPoints

        {// start property "NumberOfPoints"

            get

            { return this.noOfPoints; }

            set

            { this.noOfPoints = value; }

        }// end property "NumberOfPoints"

 

        #endregion // End of region definiton for Properties

 

        #region IFFT -> CONSTRUCTORS

        /// <summary>

        /// Initialize an new instance of an IFFT object using the "complexArray" argument

        /// to populate the array to be transformed.

        /// </summary>

        /// <param name="complexArray">An array of Complex types to be transformed.</param>

        public IFFT(Complex[] complexArray) : base(complexArray)

        {// start "IFFT(Complex[] complexArray)"

            this.inputArray = complexArray;

            this.noOfPoints = complexArray.Length;

            this.modifiedArray = new Complex[this.noOfPoints];

        }// end "IFFT(Complex[] complexArray)"

 

        /// <summary>

        /// Initialize an new instance of an IFFT object using the "complexArray" argument

        /// to populate the array to be transformed and the "noOfPoints" argument to set

        /// the number of points used in the calculation.

        /// </summary>

        /// <param name="complexArray">An array of Complex types to be transformed.</param>

        /// <param name="noOfPoints">32-bit representation of the number of FFT points to be used.</param>

        public IFFT(Complex[] complexArray, Int32 noOfPoints) : base(complexArray, noOfPoints)

        {// start "IFFT(Complex[] complexArray, Int32 noOfPoints)"

            try

            {

                this.inputArray = complexArray;

                this.noOfPoints = noOfPoints;

                this.modifiedArray = new Complex[this.noOfPoints];

 

                if (noOfPoints <= 0)

                    throw new FourierTransformException("The number of points must be greater than 0");

            }

            catch (FourierTransformException ex)

            {

                Console.WriteLine(ex.Message.ToString());

            }

        }// end "IFFT(Complex[] complexArray, Int32 noOfPoints)"

        #endregion // End region definition for Constructors

 

        #region IFFT -> METHODS

        public Complex[] Ifft()

        {// start method "public Complex[] Ifft()"

 

            // First:

            //

            Complex[] padIfft = ZeroPad();

 

            Complex[] timeDomain = DoIFFT();

 

            return timeDomain;

 

        }// end method "public Complex[] Ifft()"

 

 

        //        1    N

        // x(n) = - * SUM X(k) * Exp(j * 2 * PI * k * n / N)        1 <= n <= N

        //        N   n=0

        // and Euler's Identity:

        //       j*theta

        //      e        = cos(theta) + j * sin(theta)

        //

        /// <summary>

        /// The actual IFFT computations are done within this method.

        /// </summary>

        /// <returns>Returns an array of Complex values that have been transformed

        /// using the Inverse Fourier Transformation technique.</returns>

        /// <remarks>This method is provided in order to provide users with a finer

        /// grain of control at each step of the calculations.</remarks>

        public Complex[] DoIFFT()

        {// start method "public Complex[] DoIFFT()"

 

            // get the modified array to be operated on from

            //  the base class property

            Complex[] paddedArray = base.ModifiedArray; /*this.ModifiedArray;)*/

 

            // create storage for the resulting transformed output

            Complex[] timeDomain = new Complex[paddedArray.Length];

 

            // get the number of points used in the IFFT calculation

            Int32 points = paddedArray.Length;

 

            for (Int32 n = 0; n < points; n++)

            {// start for with n=0

 

 

                // temp1 will hold the results of the inner interations

                //  below and it is reset on each outer iteration

                Complex temp1 = new Complex(0, 0);

 

                for (Int32 k = 0; k < points; k++)

                {// start for with k=0

 

                    // local variable to compute each iteration of

                    //  X(k) * exp(...)

                    Complex temp2 = new Complex(0, 0);

 

                    // local variables to hold the result of each

                    //  part of the Euler Identity portion of the

                    //  FFT transformaton equation

                    Double real_part = 0;   // cos(theta)

                    Double imag_part = 0;   // sin(theta)

 

                    real_part = Math.Cos((2 * Math.PI * n * k) / points);

                    imag_part = Math.Sin((2 * Math.PI * n * k) / points);

 

                    temp2.Real = real_part;    // set the Real and Imaginary properties of the local

                    temp2.Imaginary = imag_part;//  Complex object uses to keep track of computations

 

                    // x(n) = [cos(T) + j Sin(T)] * X(k)

                    temp2 = temp2 * paddedArray[k];

                    temp1 = temp1 + temp2;  // sum each successive iteration

 

 

                }//end for with k=0

 

                timeDomain[n] = (temp1) / points;

 

            }// end for with n=0

 

            return timeDomain;

        }// end method "public Complex[] DoIFFT()"

 

        /// <summary>

        /// Overriden version of the System.Object.Equals() method.

        /// </summary>

        /// <param name="obj">Object type to be compared to.</param>

        /// <returns>Returns true if the current object and the argument 'obj' are equal and false otherwise.</returns>

        public override Boolean Equals(Object obj)

        {

            if (obj == null)

                return false;

            if (obj is IFFT)

            { return this == (IFFT)obj; }

            else

            { return false; }

        }

 

        /// <summary>

        /// Overidden version of System.Object.GetHashCode() method.

        /// </summary>

        /// <returns>A hash code for the current IFFT object.</returns>

        public override Int32 GetHashCode()

        {

            return base.GetHashCode();

        }

        #endregion // End region definiton for DoIFFT()

 

    }// end of class "IFFT"

    #endregion // End region definition for Class IFFT

 

    #region Start of Class "FourierTransformException"

    public class FourierTransformException : Exception

    {// start definiton of Class "FourierTransformException"

        public FourierTransformException() : base() { }

        public FourierTransformException(String message) : base(message) { }

    }// end definiton of Class "FourierTransformException"

    #endregion End of CLASS "FourierTransformException"

}