C# Get all days in a week by given date

Wrote a little DateTime extension where you can get the range of days in a week by a given date.

So for example, today is 02/26/2013, Tuesday and you want to get the range of dates in the current week which is 02/25/2013 Sunday to 03/02/2013 Saturday. I made an extension to achieve that.

Here's the DateTime Extension code

public static class Extension_DateTime
{
	public static List<DateTime> GetDaysInWeek(this DateTime Date, DayOfWeek firstdayofweek)
	{
		List<DateTime> d = new List<DateTime>();

		int days = Date.DayOfWeek - firstdayofweek;
		DateTime dt = Date.AddDays(-days);
		d.Add(dt);
		d.AddRange(new DateTime[] { dt.AddDays(1), dt.AddDays(2), dt.AddDays(3), dt.AddDays(4), dt.AddDays(5), dt.AddDays(6) });

		return d;
	}
}

Here's how to use it

static void Main(string[] args)
{
	int curr_day = DateTime.Today.Day;

	foreach (DateTime d in DateTime.Now.GetDaysInWeek(CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek))
	{
		Console.Write(d.Day + " ");
	}

	Console.ReadLine();
}
Click here to expand the blog post

C# Model Snippet for MVVM Light

Here's a little snippet for MVVM Light that you can use to lessen your work typing your properties in your Model class

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
      <Title>MVVM Model for MVVM Light</Title>
      <Author>Jayson Ragasa</Author>
      <Description>MVVM Model for MVVM Light</Description>
      <HelpUrl>
      </HelpUrl>
      <Shortcut>nm</Shortcut>
    </Header>
    <Snippet>
      <Declarations>
        <Literal Editable="true">
          <ID>type</ID>
          <ToolTip>Property Type</ToolTip>
          <Default>int</Default>
          <Function>
          </Function>
        </Literal>
        <Literal Editable="true">
          <ID>field</ID>
          <ToolTip>Private Field</ToolTip>
          <Default>myProperty</Default>
          <Function>
          </Function>
        </Literal>
        <Literal Editable="true">
          <ID>m</ID>
          <ToolTip>Lambda Parameter</ToolTip>
          <Default>m</Default>
          <Function>
          </Function>
        </Literal>
        <Literal Editable="true">
          <ID>property</ID>
          <ToolTip>Property Name</ToolTip>
          <Default>MyProperty</Default>
          <Function>
          </Function>
        </Literal>
		<Literal Editable="true">
          <ID>default_value</ID>
          <ToolTip>Default Value</ToolTip>
          <Default>0</Default>
          <Function>
          </Function>
        </Literal>
      </Declarations>
      <Code Language="csharp"><![CDATA[private $type$ _$property$ = $default_value$;
public $type$ $property$
{
    get { return _$property$; }
    set
    {
		if(_$property$ != value)
		{
			_$property$ = value;
			base.RaisePropertyChanged("$property$");
		}
    }
}]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>
Click here to expand the blog post

Myriad

OLA!!!!!

Click here to expand the blog post

Dockable Youtube Desktop Player

This is a very simple and a very basic Youtube desktop layer that sometimes useful when you're like watching something and at the same time working on something. The application can play Youtube video, stays on top and can also resize the window and dock the player anywhere on your screen. You can also change the video quality.

Download setup file in my box

DockableYoutubeDesktopPlayerSetup.exe 313.5KB

Click here to expand the blog post

C# Windows 8 App - Tile Builder

With the recent projects I had in Windows 8 App, I had to incorporate tile updates locally, taking the newest projects for the day, and show them on the tile. So I made it, got some few UI updates, as well as how the tile would look like. I always a fan of "reusable codes" so whenever I need some special functionality on other projects, I could always get this "reusable code" and just use it right away, make some updates and add some features. With this ever changing requirements of how do tile would look like, I said to my self, "hey, why not just write a small wrapper that can help me update the tile template easier", so I made TileBuilder.

TileBuilder helps you create your animated tile, have multiple tile templates, and update your tile easily. Just add your images and texts on the collection and apply any tile template you want.

Here's the 25:07 minutes video showing how to use TileBuilder

TileBuilder code

/*
 * TileBuilder v1.0
 * Jayson Ragasa
 * http://wall.jaysonragasa.net
 */

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;

namespace Capploud
{
    public class TileBuilder : INotifyPropertyChanged
    {
        #region // Vars /

        TileUpdater tileupdate = TileUpdateManager.CreateTileUpdaterForApplication();

        #endregion

        #region // Properties /

        bool _cycle = true;
        public bool Cycle
        {
            get { return this._cycle; }
            set
            {
                if (this._cycle != value)
                {
                    this._cycle = value;
                    this.tileupdate.EnableNotificationQueue(value);
                }
            }
        }

        double _expire = 0;
        public double Expire
        {
            get { return this._expire; }
            set
            {
                if (this._expire != value)
                {
                    this._expire = value;
                }
            }
        }

        //TileTemplateType _widetiletemplate = TileTemplateType.TileWideImageAndText01;
        //public TileTemplateType WideTileTemplate
        //{
        //    get { return this._widetiletemplate; }
        //    set
        //    {
        //        if (this._widetiletemplate != value)
        //        {
        //            this._widetiletemplate = value;
        //            OnPropertyChanged("WideTileTemplate");
        //        }
        //    }
        //}

        //TileTemplateType _squaretiletemplate = TileTemplateType.TileWideImageAndText01;
        //public TileTemplateType SquareTileTemplate
        //{
        //    get { return this._squaretiletemplate; }
        //    set
        //    {
        //        if (this._squaretiletemplate != value)
        //        {
        //            this._squaretiletemplate = value;
        //            OnPropertyChanged("SquareTileTemplate");
        //        }
        //    }
        //}

        Model_TileDetails _tiledet = new Model_TileDetails();
        public Model_TileDetails TileDetailColelction
        {
            get { return this._tiledet; }
            set
            {
                this._tiledet = value;
                OnPropertyChanged("TileDetailColelction");
            }
        }

        List<XmlElement> _xmlnodecoll = new List<XmlElement>();
        List<XmlElement> XmlNodeCollection
        {
            get { return this._xmlnodecoll; }
            set
            {
                this._xmlnodecoll = value;
                OnPropertyChanged("TileDetailColelction");
            }
        }

        #endregion

        #region // Constructor /

        public TileBuilder()
        {
            this.tileupdate.EnableNotificationQueue(true);

            this.tileupdate.Clear();
        }

        #endregion

        #region // Support Singleton /
        static readonly TileBuilder _i = new TileBuilder();
        public static TileBuilder I { get { return _i; } }
        #endregion

        #region // Methods /

        public void ClearTile()
        {
            this.tileupdate.Clear();
        }

        public void ClearCollection()
        {
            this.TileDetailColelction.ImageFiles.Clear();
            this.TileDetailColelction.Texts.Clear();
        }

        /// <summary>
        /// obsolete
        /// </summary>
        public void BuildTile()
        {
            string sxml = "<title><visual lang=\"en-US\">";

            foreach (XmlElement node in XmlNodeCollection)
            {
                sxml += node.GetXml();
            }

            sxml += "</visual></title>";

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(sxml);
            var tileNotification = new TileNotification(xml);
            if (Expire != 0)
            {
                tileNotification.ExpirationTime = DateTimeOffset.UtcNow.AddSeconds(Expire);
            }
            this.tileupdate.Update(tileNotification);
            
            ShowXML(xml);
        }

        public void BuildTile(TileTemplateType TileTemplate)
        {
            AddTileTemplate(TileTemplate);
        }

        public void AddTileTemplate(TileTemplateType TileTemplate)
        {
            XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplate);

            // get "image" and "text" element in <binding> node
            XmlNodeList tileImageNode = tileXml.GetElementsByTagName("image");
            XmlNodeList tileTextNode = tileXml.GetElementsByTagName("text");

            // make sure there are image nodes
            if (tileImageNode.Count > 0)
            {
                // add blank image items in our collection
                if (tileImageNode.Count > TileDetailColelction.ImageFiles.Count)
                {
                    int diff = tileImageNode.Count - TileDetailColelction.ImageFiles.Count;
                    // add blank items
                    for (int i = 0; i < diff; i++)
                    {
                        this.TileDetailColelction.ImageFiles.Add(new Model_ImageTileDetails()
                        {
                            ImageFile = string.Empty,
                            Alt = string.Empty
                        });
                    }
                }

                // finally set all necessary attribute values
                for (int i = 0; i < tileImageNode.Count; i++)
                {
                    Model_ImageTileDetails mid = TileDetailColelction.ImageFiles[i];

                    ((XmlElement)tileImageNode[i]).SetAttribute("src", mid.ImageFile);
                    ((XmlElement)tileImageNode[i]).SetAttribute("alt", mid.Alt);
                }
            }

            // make sure there are text nodes
            if (tileTextNode.Count > 0)
            {
                // add blank image items
                if (tileTextNode.Count > TileDetailColelction.Texts.Count)
                {
                    int diff = tileTextNode.Count - TileDetailColelction.Texts.Count;
                    // add blank items
                    for (int i = 0; i < diff; i++)
                    {
                        this.TileDetailColelction.Texts.Add(string.Empty);
                    }
                }

                // finally set all necessary attribute values
                for (int i = 0; i < tileTextNode.Count; i++)
                {
                    ((XmlElement)tileTextNode[i]).InnerText = TileDetailColelction.Texts[i];
                }
            }

            //IXmlNode node = tileXml.ImportNode(tileXml.GetElementsByTagName("binding").Item(0), true);
            IXmlNode node = tileXml.SelectSingleNode("//binding");

            XmlNodeCollection.Add((XmlElement)node);
            //return node;

            var tileNotification = new TileNotification(tileXml);
            if (Expire != 0)
            {
                tileNotification.ExpirationTime = DateTimeOffset.UtcNow.AddSeconds(Expire);
            }
            this.tileupdate.Update(tileNotification);
        }

        public void ShowXML(XmlDocument xmldoc)
        {
            Debug.WriteLine(xmldoc.GetXml());
        }

        #endregion

        #region INotifyPropertyChanged implementation

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            var eventHandler = this.PropertyChanged;
            if (eventHandler != null)
            {
                eventHandler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

        #region // Class Models /

        public class Model_ImageTileDetails : INotifyPropertyChanged
        {
            string _imagefile = string.Empty;
            public string ImageFile
            {
                get { return this._imagefile; }
                set
                {
                    if (this._imagefile != value)
                    {
                        this._imagefile = value;
                        OnPropertyChanged("ImageFile");
                    }
                }
            }

            string _alt = string.Empty;
            public string Alt
            {
                get { return this._alt; }
                set
                {
                    if (this._alt != value)
                    {
                        this._alt = value;
                        OnPropertyChanged("Alt");
                    }
                }
            }

            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged(string propertyName)
            {
                var eventHandler = this.PropertyChanged;
                if (eventHandler != null)
                {
                    eventHandler(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }

        public class Model_TileDetails : INotifyPropertyChanged
        {
            ObservableCollection<Model_ImageTileDetails> _imagefile = new ObservableCollection<Model_ImageTileDetails>();
            public ObservableCollection<Model_ImageTileDetails> ImageFiles
            {
                get { return this._imagefile; }
                set
                {
                    this._imagefile = value;
                    OnPropertyChanged("ImageFiles");
                }
            }

            ObservableCollection<string> _text = new ObservableCollection<string>();
            public ObservableCollection<string> Texts
            {
                get { return this._text; }
                set
                {
                    this._text = value;
                    OnPropertyChanged("Texts");
                }
            }

            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged(string propertyName)
            {
                var eventHandler = this.PropertyChanged;
                if (eventHandler != null)
                {
                    eventHandler(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }

        #endregion
    }
}

Usage

There are 2 basic properties that you need to consider before creating your new tile.

TileBuilder.Cycle (bool)

  • true - this will tell TileUpdater to have its notification queue enabled.
  • false - this will tell TileUpdater to have its notification queue disabled.

TileBuilder.Expire (double)

  • 0 - tile does not expire
  • >0 - tile does expire

After you have set those two properties. Make sure to call ClearTile() method to make sure the old tile template is cleared.

To start creating your tile, you need to use TileDetailsCollection. This property contains two collection object.

  • ImageFiles(Model_ImageTileDetails)
    • And in this Model_ImageTileDetails object, it has two properties that is needed for your image tiles
      • ImageFile
      • Alt
  • Texts(string)

Usage

TileBuilder tiler = new TileBuilder()
{
	Cycle = true,
	Expire = 0
};
tiler.ClearTile();

TileSquareBlock template

tiler.TileDetailColelction.Texts.Add(DateTime.Today.Day.ToString());
tiler.TileDetailColelction.Texts.Add(DateTime.Today.ToString("MMMM yyyy"));
tiler.BuildTile(TileTemplateType.TileSquareBlock);

TileWidePeekImageCollection05 template

tiler.TileDetailColelction.ImageFiles.Add(new TileBuilder.Model_ImageTileDetails()
{
	ImageFile = "ms-appx:///images/widetile1.jpg",
	Alt = "Wide Tile One"
});
tiler.TileDetailColelction.ImageFiles.Add(new TileBuilder.Model_ImageTileDetails()
{
	ImageFile = "ms-appx:///images/widetile2.jpg",
	Alt = "Wide Tile Two"
});
tiler.TileDetailColelction.ImageFiles.Add(new TileBuilder.Model_ImageTileDetails()
{
	ImageFile = "ms-appx:///images/widetile3.jpg",
	Alt = "Wide Tile Three"
});
tiler.TileDetailColelction.ImageFiles.Add(new TileBuilder.Model_ImageTileDetails()
{
	ImageFile = "ms-appx:///images/widetile4.jpg",
	Alt = "Wide Tile Four"
});
tiler.TileDetailColelction.ImageFiles.Add(new TileBuilder.Model_ImageTileDetails()
{
	ImageFile = "ms-appx:///images/widetile5.jpg",
	Alt = "Wide Tile Five"
});

tiler.TileDetailColelction.Texts.Add("Big Header Here");
tiler.TileDetailColelction.Texts.Add("Line 2");

tiler.BuildTile(TileTemplateType.TileWidePeekImageCollection05);

 

Changing the tile layout only requires you to change the TileTemplateType value in BuildTile

You can download the source in my box drive

TileTest.zip (69.6kb) 

Click here to expand the blog post

Image File Beautifier Application

Image File Beautifier is an application that organizes your JPEG image files into a folder by moving them on their specific year and specific month folders. It can also rename the JPEG files using date format.

Image File Browser can read JPEG file Date Taken ExIf information and with this information, the application can decide where to move the image file as well as how to name it using any of 16 different date formats.

Download

You can download the trial version here. The application is limited only to 500 renames

Buy Now for only $10!!

Product Screenshots

Features

  • Can read JPEG ExIf information
  • Multi-threaded to support processing multiple folders and files
  • Drag-Drop functionality

Here's a short product video

 
Click here to expand the blog post

C# Enumerate Special Folders

This is just a simple code to enumerate all the special folders.

using System;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (Environment.SpecialFolder sf in Enum.GetValues(typeof(Environment.SpecialFolder)))
            {
                Debug.WriteLine(string.Format("{0} - {1}", sf, Environment.GetFolderPath(sf)));
            }
        }
    }
}

make sure to check the Output pane.

Here's the preview of my Special Folders in Windows 7

Desktop = C:\Users\jaysonragasa\Desktop
Programs = C:\Users\jaysonragasa\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
MyDocuments = C:\Users\jaysonragasa\Documents
MyDocuments = C:\Users\jaysonragasa\Documents
Favorites = C:\Users\jaysonragasa\Favorites
Startup = C:\Users\jaysonragasa\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Recent = C:\Users\jaysonragasa\AppData\Roaming\Microsoft\Windows\Recent
SendTo = C:\Users\jaysonragasa\AppData\Roaming\Microsoft\Windows\SendTo
StartMenu = C:\Users\jaysonragasa\AppData\Roaming\Microsoft\Windows\Start Menu
MyMusic = C:\Users\jaysonragasa\Music
MyVideos = C:\Users\jaysonragasa\Videos
DesktopDirectory = C:\Users\jaysonragasa\Desktop
MyComputer = 
NetworkShortcuts = C:\Users\jaysonragasa\AppData\Roaming\Microsoft\Windows\Network Shortcuts
Fonts = C:\Windows\Fonts
Templates = C:\Users\jaysonragasa\AppData\Roaming\Microsoft\Windows\Templates
CommonStartMenu = C:\ProgramData\Microsoft\Windows\Start Menu
CommonPrograms = C:\ProgramData\Microsoft\Windows\Start Menu\Programs
CommonStartup = C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
CommonDesktopDirectory = C:\Users\Public\Desktop
ApplicationData = C:\Users\jaysonragasa\AppData\Roaming
PrinterShortcuts = C:\Users\jaysonragasa\AppData\Roaming\Microsoft\Windows\Printer Shortcuts
LocalApplicationData = C:\Users\jaysonragasa\AppData\Local
InternetCache = C:\Users\jaysonragasa\AppData\Local\Microsoft\Windows\Temporary Internet Files
Cookies = C:\Users\jaysonragasa\AppData\Roaming\Microsoft\Windows\Cookies
History = C:\Users\jaysonragasa\AppData\Local\Microsoft\Windows\History
CommonApplicationData = C:\ProgramData
Windows = C:\Windows
System = C:\Windows\system32
ProgramFiles = C:\Program Files
MyPictures = C:\Users\jaysonragasa\Pictures
UserProfile = C:\Users\jaysonragasa
SystemX86 = C:\Windows\system32
ProgramFilesX86 = C:\Program Files
CommonProgramFiles = C:\Program Files\Common Files
CommonProgramFilesX86 = C:\Program Files\Common Files
CommonTemplates = C:\ProgramData\Microsoft\Windows\Templates
CommonDocuments = C:\Users\Public\Documents
CommonAdminTools = C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools
AdminTools = C:\Users\jaysonragasa\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Administrative Tools
CommonMusic = C:\Users\Public\Music
CommonPictures = C:\Users\Public\Pictures
CommonVideos = C:\Users\Public\Videos
Resources = C:\Windows\resources
LocalizedResources = 
CommonOemLinks = 
CDBurning = C:\Users\jaysonragasa\AppData\Local\Microsoft\Windows\Burn\Burn
Click here to expand the blog post

Windows Phone - Close application like Windows 8

This is just a little experiment in Windows Phone where I can drag the application from top to bottom to close.. Just like Windows 8 App.

Cool right?

I just took my WPF code and implemented it in Windows Phone to see what it looks like but I think it's cool to see something like that. 

Here's a video preview of the app

You can download the code and play with it. You can also use this in your WPF applications since the code is written in MVVM pattern. Just make sure to add WPF in your Conditional Compilation Symbols.

So how to use?

Let's check out the XAML first

<Grid x:Name="LayoutRoot" Background="Transparent">
	<!-- we need canvas so we can use the Top and Left property instead of dealing with Margins -->
	<Canvas>
		<Grid x:Name="MainContent" Canvas.Top="0" Canvas.Left="0" Width="480" Height="760" Background="#FF137900">
			<Grid.RowDefinitions>
				<RowDefinition Height="Auto"/>
				<RowDefinition Height="*"/>
			</Grid.RowDefinitions>
	
			<!--TitlePanel contains the name of the application and page title-->
			<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
				<TextBlock x:Name="ApplicationTitle" Text="Start dragging here from top to bottom" Style="{StaticResource PhoneTextNormalStyle}"/>
				<TextBlock x:Name="PageTitle" Text="ala Windows 8" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
			</StackPanel>

			<!--ContentPanel - place additional content here-->
			<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"></Grid>
		</Grid>

		<!-- our drag bar which is just sitting on top -->
		<Grid x:Name="DragBar" Height="45" Canvas.Top="0" Canvas.Left="0" Background="Transparent" Cursor="Hand" />
	</Canvas>
</Grid>

If you notice, I used Canvas element, because using it is much easier for dealing with child element locations just by using Top and Left properties. It's important that the DragBar grid has to be the last child so it will always stay at the top of other child elements in the Canvas.

Since the code is fairly written in MVVM, you can just it by implementing the iDragComponents interface and instantiating ViewModel_DragComponents class

public partial class MainPage : PhoneApplicationPage, iDragComponents
{
	ViewModel_DragComponents dragcomp;

	// Constructor
	public MainPage()
	{
		InitializeComponent();
		InitializeObjects();
	}

	void InitializeObjects()
	{
		this.dragcomp = new ViewModel_DragComponents(this);
		this.dragcomp.HasToClose += new HasToCloseHandler(dragcomp_HasToClose);
		this.dragcomp.Distance = 200;
	}
	
	// has reached the distance
	void dragcomp_HasToClose(object o, EventArgs e)
	{
		NavigationService.GoBack();
	}

	#region iDragComponents implementation
	public Grid ContentGrid
	{
		get { return this.MainContent; }
		set { this.MainContent = value; }
	}
	public Grid DragBarGrid
	{
		get { return this.DragBar; }
		set { this.DragBar = value; }
	}
	#endregion
}

and so just simple as that.

You can download the code in my Box 

 http://liit.co.nr/?0l6n8

Click here to expand the blog post

Javascript Custom Loader and Bootstrap

I was doing some test about implementing my custom bootstrap and kernel in Javascript and I wanted to load them asynchronously because inside those files, there are other stuff being loaded in runtime. I tried looking for some answers to load the scripts files asynchronously but some of them are using jQuery and some were not useful. I really like like to get away with jQuery with my loader so I made my own using queueing technique just like what I used to do in C# using Queue<T>

Here's the sample loader I made

function loadFile(url, callback) {
    var head;
    var element;

    if (url.indexOf('.css') != -1) {
	head = document.getElementsByTagName('head')[0];
        element = document.createElement('link');
        element.setAttribute('type', 'text/css');
        element.setAttribute('href', url);
        element.setAttribute('rel', 'stylesheet');
    }
    else if (url.indexOf('.js') != -1) {
	head = document.getElementsByTagName('body')[0];
        element = document.createElement('script');
        element.setAttribute('type', 'text/javascript');
        element.setAttribute('src', url);
    }
    /*else I'll try to add more here soon*/

    /*bind the event to the callback function*/
    {
		/*http://www.nczonline.net/blog/2009/06/23/loading-javascript-without-blocking/*/
        if (script.readyState){  /*IE*/
			script.onreadystatechange = function(){
				if (script.readyState == "loaded" ||
						script.readyState == "complete"){
					script.onreadystatechange = null;
					callback();
				}
			};
		} else {  /*Others*/
			script.onload = function(){
				callback();
			};
		}
    }

    /*fire the loading*/
    {
        head.appendChild(element);
    }
}

{ // ENQUEUE / DEQUEUE files for asyncloading
    var d = new Date();

    // enqueue files
    var files = new Array(
        "css/jquery.metro.css",
        "css/common2.css",
        "scripts/appmanifest.js",
        "scripts/kernel.js",
        "scripts/bootstrap.js"
    );

    // dequeue
    var ready = false;
    var callback = function () {
        // file is now loaded
        // call LoadFiles() again for dequeueing 
        LoadFiles();
    };
    function LoadFiles() {
        if (files.length != 0) {
            // load file and add time so browser thinks
            // we are loading a different file
            // in other words, I hate caching them while debugging
            var file = files[0] + '?t=' + d.getTime();

            // load the file
            loadFile(file, callback);

            // dequeue the file
            files.splice(0, 1);
        }
        else {
            ready = true;
        }
    }
}

In my code above, if you notice, the function tries to insert CSS on HEAD and Javascript on BODY so why is that? It's been a practice that whenever we load a script file in our web pages, we have to put them inside the HEAD to make sure our script variables, functions, etc are defined first. I have no problem with that, if you want to use my loader script, and insert the script in head, then that's fine. Though I haven't answered the question why would I like to insert the script in the BODY? The reason is very simple, I want to make sure every element written manually or inserted dynamically exists first before doing any changes at the elements at runtime. 

you can also use Push() and Shift() in in Javascript like this one

{ // ENQUEUE / DEQUEUE files for asyncloading
    var d = new Date();

    // enqueue files
    var queue = [];
    queue.push("css/jquery.metro.css");
    queue.push("css/common2.css");
    queue.push("scripts/appmanifest.js");
    queue.push("scripts/kernel.js");
    queue.push("scripts/bootstrap.js");

    // dequeue
    var ready = false;
    var callback = function () {
        // file is now loaded
        // call LoadFiles() again for dequeueing 
        LoadFiles();
    };
    function LoadFiles() {
        if (queue.length != 0) {
            // load file and add time so browser thinks
            // we are loading a different file
            // in other words, I hate caching them while debugging
            var f = queue.shift(); // dequeue
            var file = f + '?t=' + d.getTime();

            // load the file
            loadFile(file, callback);
        }
        else {
            ready = true;
        }
    }
}

So why would I create a new bootstrap instead of using the one the was already made? The reason of that is because I really don't need everything on those offered bootstrap and loading the unnecessary libraries will just cause another webpage slowdown. My bootstrap is pretty simple, and it loads just the necessary libraries that I need which is defined in my appmanifest.js. So what on earth is appmenifest.js? App Manifest was just a small implementation of what was originally used in Siverlight, Windows Phone, and in Windows 8. Here, you can add the deployment details or any other information you need in your application.

Here's what my appmanifest.js looks like

/*
CAPABILITIES
------------
CAP_METROPIVOT
CAP_KNOCKOUT
*/
var Capabilities = [];
/*Capabilities.push("CAP_KNOCKOUT");*/
Capabilities.push("CAP_METROPIVOT");

var LayoutFiles = [];
LayoutFiles.push("scripts/View/Layout.js");

var MVVMFiles = [];
MVVMFiles.push("scripts/ViewModel/CommonViewModel.js");

and finally my bootstrap.js

/*
bootstrap.js
written by: Jayson Ragasa
*/

var d = new Date();

{ // async load required libraries    
    var required_libs = [];
    required_libs.push('scripts/Libraries/jquery-1.7.1.min.js');

    // load capabilities
    for (var i = 0; i < Capabilities.length; i++) {
        var cap = Capabilities[i];

        if (cap == "CAP_METROPIVOT") {
            required_libs.push('scripts/Libraries/Capabilities/jquery.metro.js');
            required_libs.push('scripts/Libraries/Capabilities/jquery.metro.extension.js');
        }
        else if (cap == "CAP_KNOCKOUT") {
            required_libs.push('scripts/Libraries/Capabilities/knockout.min.js');
        }
    }

    function callback_library_loaded(a) {
        LoadLibrary();
    }
    function LoadLibrary() {
        //alert(required_libs.length);

        if (required_libs.length != 0) {
            var lib = required_libs.shift();
            var f = lib + '?t=' + d.getTime() + '&ref=bootstrap';
            loadScript(f,
                function () {
                    callback_library_loaded(lib);
                }
            );
        }
        else {
            LibrariesLoaded();
        }
    }
    
    // call once;
    LoadLibrary();
}

function LibrariesLoaded() {
    required_libs.length = 0;

    { // add script files for layout
        // render layout
        for (var i = 0; i < LayoutFiles.length; i++) {
            var f = LayoutFiles[i];
            //loadScript(f, function () { });
            required_libs.push(f);
        }

        // load MVVM files
        for (var i = 0; i < MVVMFiles.length; i++) {
            var f = MVVMFiles[i];
            required_libs.push(f);
        }

        RenderLayout();
    }
}

 // load layout files and mvvm files
function callback_renderfiles_loaded(a) {
    RenderLayout();
}
function RenderLayout() {
    if (required_libs.length != 0) {
        var lib = required_libs.shift();
        var f = lib + '?t=' + d.getTime() + '&ref=bootstrap.renderfiles';
        loadScript(f,
            function () {
                callback_renderfiles_loaded(lib);
            }
        );
    }
    else {
            
    }
}

so simple isn't it? But I am hoping my custom bootstrap.js can go further as well as my kernel.js? Why on earth do I need kernel.js? I believe here in kernel.js, I can put all the necessary functions needed for my web application development. 

Here's where I implemented the whole thing C.app.loud development

Click here to expand the blog post

WPF Convert Visual Element to Encoded Image

public enum ImageEncodeType
{
	BMP, PNG, JPG
}
void ToEncodedImage(UIElement elem, ImageEncodeType encodeType, string filename, int JPGQuality = 80)
{
	RenderTargetBitmap rtb = new RenderTargetBitmap(
		(int)elem.DesiredSize.Width, (int)elem.DesiredSize.Height,
		96, 96, PixelFormats.Pbgra32);
	DrawingVisual draw = new DrawingVisual();
	using (DrawingContext dc = draw.RenderOpen())
	{
		VisualBrush vb = new VisualBrush(elem);
		dc.DrawRectangle(vb, null, new Rect(new Point(), new Size(elem.DesiredSize.Width, elem.DesiredSize.Height)));
	}
	rtb.Render(draw);

	using (Stream stream = File.Create(filename))
	{
		switch (encodeType)
		{
			case ImageEncodeType.BMP:
				BmpBitmapEncoder bmp = new BmpBitmapEncoder();
				bmp.Frames.Add(BitmapFrame.Create(rtb));
				bmp.Save(stream);
				break;
			case ImageEncodeType.JPG:
				JpegBitmapEncoder jpg = new JpegBitmapEncoder()
				{
					QualityLevel = JPGQuality
				};
				jpg.Frames.Add(BitmapFrame.Create(rtb));
				jpg.Save(stream);

				break;
			case ImageEncodeType.PNG:
				PngBitmapEncoder png = new PngBitmapEncoder();
				png.Frames.Add(BitmapFrame.Create(rtb));
				png.Save(stream);
				break;
		}
	}
}

RenderTargetBitmap renders a visual element in your WPF to image and you can later save it to an encoded image like BMP, JPG, or PNG as well as you can copy the image to clipboard.

Here's a simplest way of doing it

RenderTargetBitmap bitmap = new RenderTargetBitmap(visual.width, visual.height, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(visual);
PngBitmapEncoder image = new PngBitmapEncoder();
image.Frames.Add(BitmapFrame.Create(bitmap));
using (Stream fs = File.Create(filePath))
{
	image.Save(fs);
}
Click here to expand the blog post

About Jayson Ragasa

Jayson Ragasa is an Applications Developer and founder of CAPPLOUD.

Badges

Free Page Rank Tool

wall.jaysonragasa.net Webutation
Uptime Report for http://wall.jaysonragasa.net/: Last 30 days