Latest Entries »

Many mvc developers where asking on how to return multiple Models on a single view. Well its not that complex,  and here is how I did it.

First : Create the models

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcProject.Models {
     public class FirstModel : IEnumerable<FirstModel>, IList<FirstModel> {
         public string Title { get; set; }
         public string Message { get; set; }
         ...
     }
     public class SecondModel : IEnumerable<SecondModel>, IList<SecondModel> {
         public string Title { get; set; }
         public string Message { get; set; }
         ...
     }

     /*Strongly typed wrapper model*/
     public class WrapperModel {
          FirstModel firstModel;
          SecondModel secondModel;
          public WrapperModel() {
                 firstModel = new FirstModel();
                 secondModel = new SecondModel();
          }
     }
}

Second : Create our controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcProject.Models;

namespace MvcProject.Controllers {
     public class HomeController : Controller {
          public ActionResult Index() {
                WrapperModel wrapperModel = new WrapperModel();
                return View(wrapperModel);
          }
     }
}

Finally : Access our model through Razor

@model MvcProject.Models.WrapperModel
<div>
     @{
                foreach (MvcProject.Models.FirstModel fm in ViewData.Model.firstModel) {
                    <div>
                        <div id="SponsorNameContainer">@fm.Title</div>
                        <div id="SponsorMessageContainer">@fm.Message</div>
                    </div>
                }
            }
</div>
<div>
     @{
                foreach (MvcProject.Models.SecondModel sm in ViewData.Model.secondModel) {
                    <div>
                        <div id="SponsorNameContainer">@sm.Title</div>
                        <div id="SponsorMessageContainer">@sm.Message</div>
                    </div>
                }
            }
</div>

Lost the source code of a .net executable file? What will you do? Instead of searching for the missing piece which was not documented and not hosted in the version control, instead of searching for it in windows explorers for hours when you already know it cant be found, instead of blaming someone for not making a backup of it, go move and use a tool from red gate called the reflector and its add-in called reflexil.

My case was like the above, where someone forgot to make a backup of a running program, which will run forever. Its a windows application where members of a certain promotion are going to swipe their cards to the application and if they are entitled, the standalone application will print a voucher stating that they can claim these and those. The application needs to be updated by certain people monthly, and my boss asked me if there is a way to automate it? I said YES, but the problem is i dont have the source code, only the executable. I said, there has to be a way, and here is how I did it.

First, download these tools:
1. Reflector – http://www.red-gate.com/products/reflector/
2. Reflexil – http://sebastien.lebreton.free.fr/reflexil/

Lets setup reflector first.
1. Open reflector.

2. Add reflexil in the add-ins. Just go to View->AddIns and add Reflexil.Reflector.dll.

3.  Load the executable file that you need to patch.

4. Now select the function or method that you want to patch. Right-click on the reflexil pane and select Replace all with code.

5. Now lets make our changes.

Once you did the change, Right-click your loaded assembly and select save as from the context menu.

Now see the lesson? “Next time, host your code in your version control!.”

Today I was asked by my friend on how to rewrite a url for security reasons. He added that a geeky person might attempt to do something on the web application. With that in hand, I said, maybe we can try encrypting the string (QueryString) that we append to our original url. And here is how i did it.

First – Create the class that encrypts and decrypts our string.

using System.Text;
using System.Security.Cryptography;

namespace SC.Utility {
     public class Security {

     public static string Encrypt(string toEncrypt, bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

            System.Configuration.AppSettingsReader settingsReader =
                                                new AppSettingsReader();
            // Get the key from config file

            string key = (string)settingsReader.GetValue("SecurityKey",
                                                             typeof(String));
            //System.Windows.Forms.MessageBox.Show(key);
            //If hashing use get hashcode regards to your key
            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                //Always release the resources and flush data
                // of the Cryptographic service provide. Best Practice

                hashmd5.Clear();
            }
            else
                keyArray = UTF8Encoding.UTF8.GetBytes(key);

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            //set the secret key for the tripleDES algorithm
            tdes.Key = keyArray;
            //mode of operation. there are other 4 modes.
            //We choose ECB(Electronic code Book)
            tdes.Mode = CipherMode.ECB;
            //padding mode(if any extra byte added)

            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();
            //transform the specified region of bytes array to resultArray
            byte[] resultArray =
              cTransform.TransformFinalBlock(toEncryptArray, 0,
              toEncryptArray.Length);
            //Release resources held by TripleDes Encryptor
            tdes.Clear();
            //Return the encrypted data into unreadable string format
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

     public static string Decrypt(string cipherString, bool useHashing)
        {
            byte[] keyArray;
            //get the byte code of the string

            byte[] toEncryptArray = Convert.FromBase64String(cipherString);

            System.Configuration.AppSettingsReader settingsReader =
                                                new AppSettingsReader();
            //Get your key from config file to open the lock!
            string key = (string)settingsReader.GetValue("SecurityKey",
                                                         typeof(String));

            if (useHashing)
            {
                //if hashing was used get the hash code with regards to your key
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                //release any resource held by the MD5CryptoServiceProvider

                hashmd5.Clear();
            }
            else
            {
                //if hashing was not implemented get the byte code of the key
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            }

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            //set the secret key for the tripleDES algorithm
            tdes.Key = keyArray;
            //mode of operation. there are other 4 modes. 
            //We choose ECB(Electronic code Book)

            tdes.Mode = CipherMode.ECB;
            //padding mode(if any extra byte added)
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(
                                 toEncryptArray, 0, toEncryptArray.Length);
            //Release resources held by TripleDes Encryptor                
            tdes.Clear();
            //return the Clear decrypted TEXT
            return UTF8Encoding.UTF8.GetString(resultArray);
        }


       }
}

Then we have to add this security key in our web.config in appSettings section. This can be any key that is referenced by our encrypt and decrypt function.

<appSettings>
    <add key ="SecurityKey" value ="1001101011000011" />
  </appSettings>

And here is how we use it in our page. We first add a reference to our SC.Utility namespace.

using SC.Utilit;

Then on the page where we append our query string, we can do the below code.

Response.Redirect("Products.aspx/" + Security.Encrypt("category=books,sender=franco.robles,subcategoryid=horror,pricerange=100-1000", true));

And on our destination page, we can do the below code.

Response.Write(Security.Decrypt(Request.PathInfo.Substring(1), true));

Here is how it looks like on the browser after the request.

Not quite elegant solution but we did it.

The common thinking of a developer if asked for file upload and download component is to put it in a shared directory and upload it as part of a file system. But there is a more neater way of doing it and Sharepoint does it. Now, ill show you how I do it with ASP.NET.

First lets setup our page to support vb.net function call from client side using PageMethods.

.....
<form id="frmStrive" runat="server">
<asp:ScriptManager ID="scriptManager" runat="server" EnablePageMethods="true" />
<asp:FileUpload ID="fileUpload" runat="server" Width="100%" onchange="PutDescOnParent(this.value);"/>
...

right after our form tag is we created a scriptmanager and the most important thing is that we set EnablePageMethods=”true” which will do the trick.

Next we set up our client side code.

function onUploadClick(){
            if ($j("#txtUploadDesc").val() == '') {
                alert("Please put a description for this file.");
                return;
            }
    
            var vaild = fileUpload.value.length > 0;
            if(vaild){
                //  disable the upload button
                $get('upload').disabled = 'disabled';
                
                //  update the message
                updateMessage('info', 'Initializing upload ...');
                PageMethods.SaveFileToDb(document.getElementById("txtUploadDesc").value);
                //  submit the form containing the fileupload
                
                form.submit();
....

Now if you’ll notice on the 14th line i called PageMethods.SaveFileToDb where it accepts one parameter and call a server side code. Lets see what it does from behind.

<System.Web.Services.WebMethod()> _
    <System.Web.Script.Services.ScriptMethod()> _
    Public Shared Sub SaveFileToDb()
        Dim files As New System.Collections.Generic.Dictionary(Of String, String)
        files = DirectCast(HttpContext.Current.Session("Files"), System.Collections.Generic.Dictionary(Of String, String))

        For Each kvp As KeyValuePair(Of String, String) In files
            Using myConnection As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("DBConnection2").ConnectionString)
                Const SQL As String = "INSERT INTO [tblFiles] (filename, filedescription, mainfile,parent) VALUES (@fileName, @fileDescription, @mainFile,@parent)"
                Dim myCommand As New System.Data.SqlClient.SqlCommand(SQL, myConnection)
                myCommand.Parameters.AddWithValue("@fileName", kvp.Key)
                myCommand.Parameters.AddWithValue("@fileDescription", kvp.Value)
                Dim im As New _HR001
                Dim fle As New System.IO.FileInfo(im.GetPath(kvp.Key))
                im.Dispose()
                Dim imageBytes(fle.Length) As Byte
                Dim s As System.IO.Stream
                s = fle.OpenRead
                s.Read(imageBytes, 0, imageBytes.Length)
                myCommand.Parameters.Add("@mainFile", Data.SqlDbType.VarBinary)
                myCommand.Parameters("@mainFile").Value = imageBytes
                myCommand.Parameters.AddWithValue("@parent", New _HR001().GetGuid())
                myConnection.Open()
                myCommand.ExecuteNonQuery()
                myConnection.Close()
            End Using
        Next kvp
    End Sub

Now what this block of code does is that it simply retrieves the path of the file(s) the we temporarily store on a session then inserts those files to a particular table which in my case named tblFiles containing a varbinary(max) field which is the container of binary files. Oh by the way during the time we started our session, we created a temporary directory on the server which is identified via creating a unique id and is achieved by the below line.

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        Dim dir As New System.IO.DirectoryInfo(Server.MapPath("~/uploads/"))
        dir.CreateSubdirectory(Session("TempDir"))
        Session("Files") = New System.Collections.Generic.Dictionary(Of String, String)
End Sub 

NOTE: In sql server 2000, you can upload up to 8mb files only, which is upgraded in sql server 2005 up. In sql server 2005 up? It depends on your disk space. Now let me show you the structure of my table.

You might be asking, after saving to sql server how will i retrieve it? Here’s how.

Using myConnection As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("DBConnection2").ConnectionString)

                Const SQL As String = "SELECT * from tblFiles where fileId=@fileId"
                Dim myCommand As New System.Data.SqlClient.SqlCommand(SQL, myConnection)
                myCommand.Parameters.AddWithValue("@fileId", HttpContext.Current.Request.QueryString("fileId"))

                myConnection.Open()
                Dim myReader As System.Data.SqlClient.SqlDataReader = myCommand.ExecuteReader

                If myReader.Read Then

                    Response.ClearContent()
                    Response.AddHeader("Content-Disposition", "attachment; filename=""" & myReader.Item("fileName") & """")

                    Dim bw As New System.IO.BinaryWriter(Response.OutputStream)
                    bw.Write(DirectCast(myReader("mainFile"), Byte()))
                    bw.Close()

                    Response.End()

                End If

                myReader.Close()
                myConnection.Close()


            End Using

See the picture? Its not quite complex. Have to continue doing my project. My next blog will be about how to convert a lousy windows forms to WPF the silverlight way.

Cool jQuery Progress Indicator

One of my projects was to develop a automated employee automation application which will use jQuery. Today I am going to show you how you can create a cool progress indicator to tell your end user that something is going on behind the back of an action. Below is an image of the progress indicator that slides from the top to the middle of the screen then displays the processing message then slides up and disappears once done.

Processing Image

The Code

<html>
<head>
	<script src="scripts/jquery.js"></script>
	<script type="text/javascript" >
		var $j = jQuery.noConflict();
		$j(document).ready(function(){
			$j("#btnSubmit").click(function(){
				$j("#messenger").css("width", document.body.offsetWidth);
        			$j("#messenger").css("height", document.body.offsetHeight);
        			$j("#messenger").css("opacity",.7);
        			$j("#messenger").fadeIn('fast');
				$j("#messengermessage").css("width", document.body.offsetWidth);
				$j("#messengermessage").animate({opacity: "1", top: "+=" + addToAnimation, height: "100", width: document.body.offsetWidth}, "slow")
        			var myhtml = '<div style="float:left; position:relative; padding-top:30px;"><img src="images/processing.gif" /></div><div style="float:left; position:relative; padding-top:40px;"><font style="font-family:verdana; font-size:14px;color:#000000; font-weight:bold;">saving attachments...</font></div>'
        			$j("#messengermessage").html("");
        			$j("#messengermessage").html(myhtml);
				$j.post('handlers/EmployeeRequisition.ashx', {
					requestedBy : GetRequestedBy(),
                    			requestor : GetRequestor(),
                    			requisitionDate : $j("#dtpRequisitionDate").val()
				},
                		function(data) {
					myhtml = '<div style="float:left; position:relative; padding-top:30px;"><img src="images/processing.gif" /></div><div style="float:left; position:relative; padding-top:40px;"><font style="font-family:verdana; font-size:14px;color:#000000; font-weight:bold;">form saved... </font></div>'
                    			$j("#messengermessage").html("");
                    			$j("#messengermessage").html(myhtml);
                    			$j("#messengermessage").animate({opacity: "1"},2000, function(res) {
                        		var subtractThis = document.body.offsetHeight - 500;
                        		$j("#messengermessage").animate({opacity: "0", top: "-=" + subtractThis, height: "0", width: document.body.offsetWidth}, "slow")
                        	        $j("#messenger").fadeOut('fast');
                    		});
			});
		});
	</script>
</head>
<body style="font-family: Verdana; margin: 0px;">
    <form id="frmHR001" runat="server">
	<div>
		............

	</div>
	<div>

		<input type="button" id="btnSubmit" value="submit" />
	</div>
	<div id="messenger" style="float: none; position: absolute; width: 100%; height: 100%;
            background-color: #000000; display: none; left: 0; top: 0;">
        </div>
        <div id="messengermessage" style="float: none; position: absolute; width: 100%; height: 100px;
            background-color: #ffffff; display: none; left: 0; top: 0; text-align: center;">
            <div style="float: left; position: relative; padding-top: 30px;">
                <img src="images/processing.gif" />
            </div>
            <div style="float: left; position: relative; padding-top: 40px;">
                <font style="font-family: Verdana; font-size: 14px; color: #000000; font-weight: bold;">
                    processing...</font>
            </div>
        </div> 
    </form>
</body>
</html>

The code is quite long but then again it achieves our purpose. Lets walk through the code and see how it happened.

1. Our Html
The fading in gray background which is initially hidden through the display:none; css attribute.

<div id="messenger" style="float: none; position: absolute; width: 100%; height: 100%;
            background-color: #000000; display: none; left: 0; top: 0;">
        </div> 

The white progress indicator with the processing image.

<div id="messengermessage" style="float: none; position: absolute; width: 100%; height: 100px;
            background-color: #ffffff; display: none; left: 0; top: 0; text-align: center;">
            <div style="float: left; position: relative; padding-top: 30px;">
                <img src="images/processing.gif" />
            </div>
            <div style="float: left; position: relative; padding-top: 40px;">
                <font style="font-family: Verdana; font-size: 14px; color: #000000; font-weight: bold;">
                    saving form...</font>
            </div>
        </div> 

The submit button which triggers the posting of data via our handler

<input type="button" id="btnSubmit" value="submit" />

2. The jQuery code the does it all.

First we reference our jquery library.

<script src="scripts/jquery.js"></script>

Second we initiate our jQuery code;

<script type="text/javascript" >
		var $j = jQuery.noConflict();
		$j(document).ready(function(){
                });
</script>

Then we assign an click event to our submit button

<script type="text/javascript" >
		var $j = jQuery.noConflict();
		$j(document).ready(function(){
			$j("#btnSubmit").click(function(){
                        });
		});
	</script>

And inside our button the gray slightly transparent background occupies the whole width of the window

$j("#messenger").css("width", document.body.offsetWidth);

then occupies the whole height of the screen

$j("#messenger").css("height", document.body.offsetHeight);

we then set its opacity

$j("#messenger").css("opacity",.7);

and then here is the fading-in animation of the gray background

$j("#messenger").fadeIn('fast');

we then tell the white sliding progress indicator to occupy the whole width of the window

$j("#messengermessage").css("width", document.body.offsetWidth);

and finally the code that makes it slide saying that our form is currently doing something

$j("#messengermessage").animate({opacity: "1", top: "+=" + addToAnimation, height: "100", width: document.body.offsetWidth}, "slow")

how does it slide up after the posting of data? just do the reverse of the latter.

$j("#messengermessage").animate({opacity: "1"},2000, function(res) {
var subtractThis = document.body.offsetHeight - 500;
$j("#messengermessage").animate({opacity: "0", top: "-=" + subtractThis, height: "0", width: document.body.offsetWidth}, "slow")

and lastly we tell the gray background to fadeout since we are done with the processing

$j("#messenger").fadeOut('fast');

Thats it. Of course there are many cool progress indicators but this one is simple and easy to understand yet nice looking. By the way there is one great javascript library asside from jQuery that you would really love. Find out how, this is there site: www.sencha.com

The Project Tracker

It’s been a long time since I havent created a blog about silverlight. Ill make this short since I have lots of things to do, not just silverlight. Today, I am going to show my latest addition to my projects “The Project Tracker”. This will show that silverlight is not just for media.

First Screen
The home screen. This window will list all the current user’s projects with Active Directory authentication.

Second Screen
The project creation screen. This window is where you save your current projects for tracking.

Third Screen
The project attachment screen. This window is where you attach supporting documents for your project.

Fourth Screen
The query screen. This window is where you will find the projects by you and your teammate and can be filtered via there status.

Fifth Screen
The history window. This window is where you will keep track of who commented or did something to your posted project.




Sixth Screen
The notification module. The highlighted object will slide up and stays for 5 seconds which acts like other notifications in the taskbar.

Now who said that silverlight is just for animations and other things. Lets make it simple and straight. If you want a rich interactive web application for your audience use Silverlight.

This morning I was having a problem in saving date type of data to sql server. The problem? If the current language of your instance is us_english then the format of the date is mdy which is month/date/year. Now my requirement was to save and display as dmy or date/month/year. When you try to save the format it will throw an error saying that you are trying to store an invalid date. How to deal with this? Follow the below steps:

1. Identify the language that is currently used by your login. How? Execute the below script in sql server.

select name, language from master.dbo.syslogins

2.  If you can find your login there then identify the date format that is being used by your login’s language which you will know by issuing the below code in sql server.

select name ,alias, dateformat
from sys.syslanguages

which retrieve the below list.


3. Then identify your requirement, in my case i need to use the British English format which is dmy or date/month/year.  Now we have to change  our login’s language by issuing the below code in sql server

SET Language British

4.  We can now pass the dmy format to date fields in sql server by using the below code in asp.net.

string.Format("{0:dd/MM/yyyy}", DateTime.Now);

I hope this post will help those who will encounter problems with date formatting.

Silverlight on Facebook

For those who want to load their Silverlight application on Facebook. These are the steps.  This is the simplest implementation that i’ve tested so far. If you have a much better implementation, then lets share for the community.

Facebook Setup

1. Login to Facebook.

2. Under Account menu, click Application Settings.

3. On the Developer row, click Profile.

4. On the Developer Profile, click Go To Application.

5. On the Profile Page, click Setup A New Application.

6. On the Create Application Page, type a name for your application and press Create Application.

7. On the Application Page, Select Canvas on the left menu.

8. Once in the Canvas Page, go to the Reguired URLs section. And provide the below parameters.

Canvas Page URL = “Name of your application”
Canvas Callback URL = “Url of the application except for the page that is hosting your silverlight app.”
Example: http://YourDomain.com/SLHost.aspx
must be http://YourDomain.com/

9. Save your Application.

IIS Settings

1. Under Default Web Site, navigate to your Application and select Features View

2. On the features view, double-click Default Document.

3. On the Default Documents, add the Web page the hosts the silverlight control.

To View Your Application

1. After saving your newly created application, click View Application Profile.

2. In the Application Profile Page, click Go To Application.

This is my sample silverlight application on facebook.

http://apps.facebook.com/grabsystem/?_fb_fromhash=c2fadd6db696955004c7711200213355

This is for those who dont know this Add-in tool yet which is very usefull when it comes to developing WCF services. I’ve been searching for this Add-In since, luckily I had a Team Lead which is not that selfish in terms of knowledge sharing. So I will do the same for those who has problems debugging their wcf service.

Okey here are the steps.

1.) Locate the add-in which resides on your installation path under \Microsoft Visual Studio 9.0\Common\IDE\WcfTestClient.exe

IE: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\WcfTestClient.exe

2.) Add WCF TestClient to your External tools under Tools > External Tools menu of VS 2008. Under the Command field, copy and paste that path of the WCFTestClient.exe. And you name the tool in the Title field like the image you see below.

Debugging Example

1.) Build your project containing the wcf service.
2.) Launch the WCTTestClient which will appear under the Tools menu of Visual Studio 2008 after adding in the external tools.

3.) Right-click “My Service Projects” and select “Add Service”

4.) Once the service is successfully added. Your service operations will be listed in the left pane. To test these service operations, just double – click the operation and press invoke.

Any breakpoint(s) in the service method which is invoked will cause a break point after pressing invoke.

Finally, our problem of testing a wcf service has been made easy with Visual Studio 2008′s WCF Test Client.

Most of us wants our RI Application to be flexible as much as possible, and at the same time compatible and is uniform to the resources that we are using. A common example for this scenario is when using a font family that is not commonly installed in the client’s computer. Now you can picture the problem. Lets say, i have a rounded font, which is widely used in all of my xaml pages and it is not pressent in the users machine. Solution? Embed the font to our application. In this article I’ll show you how to achieve that with these few lines of code.

Add your font file as embedded resource to your Siverlight Project.

1. Add font to project.

2. Set Build Action of your font file as Embedded Resource

After adding the font as embedded resource, we can now call the font in a form of a Stream. But before that, lets see the content of our xaml page.


<UserControl x:Class="EmbedFont.MainPage"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
  <Grid x:Name="LayoutRoot">
        <TextBlock x:Name="txtRoundedFont" FontSize="30" Text="Dont stop learning."/>
  </Grid>
</UserControl>

On our Xaml page we have a TextBlock named txtRoundedFont and by running the application the result will be something like this silverlight page with its default font family

Finally, in order for this to work, we need to add a loaded event on our xaml pages’ constructor.

this.Loaded += new RoutedEventHandler(MainPage_Loaded);

And inside our loaded event will be this three lines of code.

void MainPage_Loaded(object sender, RoutedEventArgs e) {
	System.IO.Stream streamedFont = this.GetType().Assembly.GetManifestResourceStream("EmbedFont.Fonts.VAGRounded-Black_0.otf");
	txtRoundedFont.FontSource = new FontSource(streamedFont);
	txtRoundedFont.FontFamily = new FontFamily("VAGRounded");
}

And here is our new TextBlock with an embedded font.

Now how did we achieve that?
First we have the below statement which loads our embedded font resource and assign that to our streamedFont identifier which is of type System.IO.Stream. Now inside our GetManifestResourceStream function is a string parameter which represents our project name “Embed.” then the folder inside our project “Embed.Fonts.” then the file name “Embed.Fonts.VAGRounded-Black.otf”.

System.IO.Stream streamedFont = this.GetType().Assembly.GetManifestResourceStream("EmbedFont.Fonts.VAGRounded-Black_0.otf");

The second line simply assigns our streamedFont bufferred data to the FontSource property of txtRoundedFont textblock.

 
 txtRoundedFont.FontSource = new FontSource(streamedFont);

Finally, we have to insert our final statment which sets the font family of our textblock.

txtRoundedFont.FontFamily = new FontFamily("VAGRounded");

NOTE: To know the exact name of a font. Double-click the file and check the font name.

Follow

Get every new post delivered to your Inbox.