Sunday, June 19, 2011

Retrieve Environment Variables

   1: ''' <summary>
   2: ''' Class to retrieve environment variables and custom declared variables with following format %VARIABLE%
   3: ''' </summary>
   4: ''' <remarks>A class used to read a string and transform all known variables with format %VARIABLE%,returning the converted string</remarks>
   5: Public Class VariableRetriever
   6:  
   7:     #Region "Methods"
   8:  
   9:     ''' <summary>
  10:     ''' Converts all known variables with format %VARIBALE% in the provided string
  11:     ''' </summary>
  12:     ''' <param name="str">Provide a string to transform</param>
  13:     ''' <returns>Returns the converted string</returns>
  14:     ''' <remarks>If an error occurs an empty string will be returned</remarks>
  15:     Protected Friend Shared Function GetAllVarFromString(ByVal str As String) As String
  16:         'try to get all the special %xxx% from the string
  17:         'replace and rebuild string
  18:         Try
  19:         
  20:             Dim split() As String = Nothing
  21:             Dim i As Integer = 0
  22:             Dim var As String = Nothing
  23:             Dim firstindex As Integer = Nothing
  24:             Dim secondindex As Integer = Nothing
  25:             If Not String.IsNullOrEmpty(str) Then
  26:                 If str.Contains("%") Then
  27:                     Do Until str.Contains("%") = False
  28:                         firstindex = Nothing
  29:                         secondindex = Nothing
  30:                         var = Nothing
  31:  
  32:                         firstindex = str.IndexOf("%")
  33:                         If Not firstindex = -1 Then
  34:                             secondindex = str.IndexOf("%", firstindex + 1)
  35:                             If Not secondindex = -1 Then
  36:                                 var = str.Substring(firstindex + 1, secondindex - firstindex - 1)
  37:                                 ReDim Preserve split(i)
  38:                                 split(i) = str.Substring(0, firstindex)
  39:                                 i = i + 1
  40:                                 ReDim Preserve split(i)
  41:                                 split(i) = GetVar(var)
  42:                                 str = str.Remove(0, secondindex + 1)
  43:                                 i = i + 1
  44:                             End If
  45:                         End If
  46:                     Loop
  47:                     ReDim Preserve split(i)
  48:                     split(i) = str
  49:                     If Not split.Length > 0 Then
  50:                         Return str
  51:                     Else
  52:                         Return Join(split, "")
  53:                     End If
  54:                 Else
  55:                     Return str
  56:                 End If
  57:             Else
  58:                 Return str
  59:             End If
  60:         Catch ex as Exception
  61:             Return ""
  62:         End Try
  63:     End Function 'End Method GetAllVarFromString
  64:  
  65:     ''' <summary>
  66:     ''' Converts a %VARIABLE% to it's value
  67:     ''' </summary>
  68:     ''' <param name="variable">Provide a variable %VARIABLE% as string</param>
  69:     ''' <returns>Returns converted string</returns>
  70:     ''' <remarks></remarks>
  71:     Protected Friend Shared Function GetVar(ByVal variable As String) As String
  72:         Try
  73:             If Not String.IsNullOrEmpty(variable) Then
  74:                 variable = RemoveProcents(variable)
  75:                 'Here you can add some variables
  76:                 'A few examples %APPPATH% will return the application startup path
  77:                 '%APPNAME% just gets the filename without extension
  78:                 Select Case UCase(variable)
  79:                     Case "APPPATH"
  80:                         Return Application.StartupPath
  81:                     Case "APPNAME"
  82:                         Return IO.Path.GetFileNameWithoutExtension(Application.ExecutablePath)
  83:                     Case Else
  84:                         Return Environment.GetEnvironmentVariable(RemoveProcents(variable))
  85:                 End Select
  86:             Else : Return variable
  87:             End If
  88:  
  89:         Catch ex As Exception
  90:             Return ""
  91:         End Try
  92:     End Function 'End Method GetVar
  93:     
  94:     ''' <summary>
  95:     ''' Removes all % characters in a string
  96:     ''' </summary>
  97:     ''' <param name="str">Provide a string</param>
  98:     ''' <returns>Returns a string with % characters stripped</returns>
  99:     ''' <remarks></remarks>
 100:     Private Shared Function RemoveProcents(ByVal str As String) As String
 101:         If Not String.IsNullOrEmpty(str) Then
 102:             str = Replace(str, "%", "")
 103:         End If
 104:         Return str
 105:     End Function 'End Method RemoveProcents
 106:  
 107: #End Region 'Methods
 108:  
 109: End Class 'End Type VariableRetriever
 110:  

Disclaimer

 
   1: #Region "Header"
   2: 'Copyright (c) 2011 <a href="http://kaoticreality.blogspot.com">Kraeven</a>
   3: '
   4: 'Knowledge needs to shared to enlighten the world ~ Kraeven ®
   5: '
   6: 'Permission is hereby granted, free of charge, to any person obtaining a copy
   7: 'of this software and associated documentation files (the "Software"), to deal
   8: 'in the Software without restriction, including without limitation the rights
   9: 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10: 'copies of the Software, and to permit persons to whom the Software is
  11: 'furnished to do so, subject to the following conditions:
  12: '
  13: 'The above copyright notice and this permission notice shall be included in
  14: 'all copies or substantial portions of the Software.
  15: '
  16: 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17: 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18: 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19: 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20: 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21: 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22: 'THE SOFTWARE.
  23:  
  24: #End Region 'Header

Thursday, March 24, 2011

What happens when you navigate to a URL?

Browse the net I found a really interesting article about what actually happens when you type in a URL in your browser.

How does the content of website makes its way to your browser for display?

Full Article : http://igoro.com/archive/what-really-happens-when-you-navigate-to-a-url/

In an nutshell:

1. You enter a URL into the browser

2. The browser looks up the IP address for the domain name

image

The first step in the navigation is to figure out the IP address for the visited domain.

3. The browser sends a HTTP request to the web server

image

4. The Facebook server responds with a permanent redirect

image 

5. The browser follows the redirect

image

The browser now knows that “http://www.facebook.com/” is the correct URL to go to, and so it sends out another GET request

6. The server ‘handles’ the request

image

The server will receive the GET request, process it, and send back a response.

7. The server sends back a HTML response

image

8. The browser begins rendering the HTML

Even before the browser has received the entire HTML document, it begins rendering the website:

image

9. The browser sends requests for objects embedded in HTML

image

10. The browser sends further asynchronous (AJAX) requests

image

Friday, March 18, 2011

Upgrade Internet Explorer 1.0 to 9.0

http://www.winrumors.com/man-upgrades-internet-explorer-1-0-to-9-0-video/

Credits go to Andrew Tait

From the same person who made the video about upgrading from windows 1.0 to 7
another nostalgic video taking us way back into Internet Explorers past.

The video shows the install processes and UI for each version of Internet Explorer.

Andrew also tested the various versions at the Acid test pages.

Wednesday, March 9, 2011

Enable Compiler Extensions in .NET 2.0

If you get an error like shown below; this is probably due to the downgrade of a project from .NET 3.5 or higher to .NET 2.0

Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll?

Extension methods are a new feature in .NET 3.5 (C#3/VB9) that let you appear to "spot weld" new methods on to existing classes.
If you think that the "string" object needs a new method, you can just add it and call it on instance variables.

But how do we accomplish this in .NET 2.0?

VB.NET

' you need this once (only), and it must be in this namespace
Namespace System.Runtime.CompilerServices
    <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.[Class] Or AttributeTargets.Method)> _
    Public NotInheritable Class ExtensionAttribute
        Inherits Attribute
    End Class
End Namespace
' you can have as many of these as you like, in any namespaces
Public NotInheritable Class MyExtensionMethods
    Private Sub New()
    End Sub
    <System.Runtime.CompilerServices.Extension> _
    Public Shared Function MeasureDisplayStringWidth(graphics As Graphics, text As String) As Integer
        ' ... 
 
    End Function
End Class

C#



// you need this once (only), and it must be in this namespace
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class
         | AttributeTargets.Method)]
    public sealed class ExtensionAttribute : Attribute {}
}
// you can have as many of these as you like, in any namespaces
public static class MyExtensionMethods {
    public static int MeasureDisplayStringWidth (
            this Graphics graphics, string text )
    {
           /* ... */
    }
}

Thursday, March 3, 2011

Upgrade Windows 1.0 to Windows 7

http://www.winrumors.com/man-upgrades-windows-1-0-to-windows-7-via-every-other-windows-versions/

I stumbled upon this video of a guy upgrading windows from the first until the last version…
Talk about backward compatibility !!!

The movie  shows all details about the installation process of each version of the windows UI from windows 1.0 until windows 7.
The only exception is Windows ME, missing as you can only upgrade to ME or 2000 and not both.

The video creator, Andrew Tait, used VMWare to install each version and started by installing MS-DOS 5.0 to prepare for the Windows 1.0 installation.

If you’re a Windows fan and have 10 minutes free then check-out the nostalgic video below,
thanks to The Next Web for spotting this classic.

Tuesday, February 15, 2011

FileDB - A C# database to store files

When browsing through the codeplex website, I found an interesting project.
A simple easy to use storage container, in the past I used QVFS
http://www.codeproject.com/KB/vb/QVFS.aspx .
But this project seems to be abandoned. This seems to be very promising, the only thing I'm missing, that is available in QVFS is the ability
to create a folder structure inside the virtual storage file. On the other hand QVFS uses 2 files, 1 info file and a data file as this FileDB uses only 1 file.

Ripped of CodePlex website : http://filedb.codeplex.com/
Credits go to mbdavid http://www.codeplex.com/site/users/view/mbdavid

 

FileDB - Project Description




FileDB is a free, fast, lightweight C# (v3.5) DLL project to store, retrieve and delete files using a single archive file as a container on disk.
It's ideal for storing files (all kind, all sizes) without databases and keeping them organized on a single disk file.



  • First stable version was launched
  • Improvements on concurrent write access
  • New method: Export - Export all files to a directory

using Numeria.IO;

var pathDB = @"C:\Temp\MyDB.fdb";

// Creating an empty FileDB archive
FileDB.CreateEmptyFile(pathDB);

// Store file from input stream
var info = FileDB.Store(pathDB, "MyFileName.jpg", inputStream);
// -or- store directly from the file itself
var info = FileDB.Store(pathDB, @"C:\Temp\MyPhoto.jpg");

// The 'info' variable returned contains information about your file (generated GUID, filename, file-length, mime-type)
var fileGuid = info.ID;

// Reading file inside FileDB and writing it on an output stream (also available to write it directly to a file)
var info = FileDB.Read(pathDB, fileGuid, outputStream);

// Deleting a file
var ok = FileDB.Delete(pathDB, fileGuid);


FileDB Methods



  • CreateEmptyFile - Create an empty data file archive
  • Store - Store from file/stream to the data file
  • Read - Search a fileID and restore it to output file/stream
  • Delete - Delete a file
  • ListFiles - List all files inside the archive
  • Shrink - Reorganize archive removing unused disk space
  • Export - Export files inside archive to a directory

All operations have a static method helper or can be used from a FileDB instance.


ASP.NET MVC Example

Below is a basic example to store/retrieve/delete information in a ASP.NET MVC Controller



private string pathDB = @"C:\Temp\MvcDemo.fdb";

// Uploading a file
[HttpPost]
public ActionResult Upload()
{
HttpPostedFileBase file = Request.Files[0] as HttpPostedFileBase;

if (file.ContentLength > 0)
FileDB.Store(pathDB, file.FileName, file.InputStream);

return RedirectToAction("Index");
}

// Download
[HttpGet]
public ActionResult Download(string id)
{
// Using a classic way to download a file, instead of FileContentResult mode.
// Optimizing for big files. Your webserver will not consume CPU/Memory to download this file (even very large files)

using (var db = new FileDB(pathDB, FileAccess.Read))
{
var info = db.Search(Guid.Parse(id));

Response.Buffer = false;
Response.BufferOutput = false;
Response.ContentType = info.MimeType;
Response.AppendHeader("Content-Length", info.FileLength.ToString());
Response.AppendHeader("content-disposition", "attachment; filename=" + info.FileName);

db.Read(info.ID, Response.OutputStream);

return new EmptyResult();
}
}


Why?


Well, all web developers already had this problem: "I need to store same user files (photos, documents, ...) and I need to save them on my web server. But where? File system or database?"
(See some discussion in http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay#3756)
The problem is: the database was not designed to store files. ADO.NET doesn't have a good method to work with streams (only byte[]).
For small files (less then 100K) it works very nice. But what happens with a 10Mb file? 100Mb? It's terrible! The solution: work on file system!
The file system has a problem too: what if my user wants to upload 300 files? And what if I have 2000 users?
You will have thousands of files to backup and manage, and this will be a pain.
My idea: a single archive (or a single archive per user) to store only user uploaded files.
I use the SQL Server database to store the ID file reference (GUID) and FileDB does the rest of the job, storing and managing the files and bytes.


How FileDB works?


FileDB was designed to be fast, very simple, file-based and works with all file sizes.
FileDB doesn't consume lots of memory because it works only with streams (no byte[]).
The data structure is built with two kinds of pages: IndexPage and DataPage.
- The IndexPage stores information about the file descriptor and it's organized in a binary tree structure.
- The DataPage stores the file bytes.

Both pages have 4096 bytes (plus 100 bytes to file header). Each page has its own header to store information about the data inside the page.
You can delete a file inside the archive and the empty data pages will be used on next insert. Or you can shrink database to get your non-used bytes.
FileDB caches (in memory) only index pages, to be faster on a second search.


Limitations

I've made many tests to check performance and limitations with all file sizes.
To protect against many clients changing data on same archive, FileDB uses read share mode.
This way many users can search/read simultaneously but only one user can write (store/delete) at a time.
FileDB class also implements IDisposable so you can use it inside a using code.


using(var db = new FileDB(pathDB, FileAccess.ReadWrite))
{
db.Store(@"C:\Temp\MyPhoto.jpg");
}



The data size limitations are based on .NET MaxValue constants. FileDB works with UInt32 (4 bytes unsigned), which limits each file to 4GB and the database to 16TB (4096 Pages * UInt32.MaxValue).

Monday, January 24, 2011

How to identify if string contain a number?

System.Text.RegularExpressions.Regex.IsMatch(input, "\d")

So times you will need to check a string, to see if it contains a number.
What’s the best way to do this?


There are several solutions like this function :

TryParse approach:



Public Shared Function IsNumeric(Expression As Object) As Boolean
    Dim isNum As Boolean
    Dim retNum As Double
    isNum = [Double].TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, retNum)
    Return isNum
End Function

Check Characters in String approach:



Public NotInheritable Class Extensions
    Private Sub New()
    End Sub
    <System.Runtime.CompilerServices.Extension> _
    Public Shared Function IsNumeric(s As String) As Boolean
        For Each c As Char In s
            If Not Char.IsDigit(c) AndAlso c <> "."C Then
                Return False
            End If
        Next
 
        Return True
    End Function
End Class

What about locales where '.' is the group separator, not the comma (e.g. pt-Br)? What about negative numbers?
Group separators (commas in English)? Currency symbols?
TryParse() can manage all of these as required using NumberStyles and IFormatProvider.

Regular Expressions approach:



System.Text.RegularExpressions.Regex.IsMatch(input, "^\d+$")

This will return true if input is all numbers


If you just want to know if it has one or more numbers mixed in with characters, leave off the ^ + and$.



System.Text.RegularExpressions.Regex.IsMatch(input, @"\d")

Actually I think it is better than TryParse because a very long string could potentially overflow TryParse.

Summary


In my opinion the winner is the Regular Expressions Method

Sunday, January 9, 2011

Secunia Personal Software Inspector (PSI)

 

Upon stumbling through the web, I found a nice tool to check the installed software for security issues and out-dated programs.
So I thought I’d shared it with you…

http://secunia.com/vulnerability_scanning/personal/

They even have an online scanning tool, so you don’t need to install the application http://secunia.com/vulnerability_scanning/online/

Screenshot PSI application :image

FREE PC Security for Home Users

The Secunia PSI is a FREE security tool designed to detect vulnerable and out-dated programs and plug-ins which expose your PC to attacks. Attacks exploiting vulnerable programs and plug-ins are rarely blocked by traditional anti-virus and are therefore increasingly "popular" among criminals.
The only solution to block these kind of attacks is to apply security updates, commonly referred to as patches.
Patches are offered free-of-charge by most software vendors, however, finding all these patches is a tedious and time consuming task.
Secunia PSI automates this and alerts you when your programs and plug-ins require updating to stay secure.
Download the Secunia PSI now and secure your PC today - free-of-charge.


Secunia PSI Watch: How to install and use the Secunia PSI 2.0

Current version:
2.0

Latest release:
5th Jan, 2011

File size:
1,737,088 bytes

Alternate download link: ftp://ftp.secunia.com/PSISetup.exe

Older version of the Secunia PSI can be downloaded at:

http://secunia.com/PSI1Setup.exe

System Requirements

The list of requirements that must be met for the Secunia PSI to function correctly are:

Supported Operating Systems (32 & 64 bit):
  • Microsoft Windows 7
  • Microsoft Windows Vista SP 1 or later
  • Microsoft Windows XP - SP 3
Privileges

To install and run the Secunia PSI you require administrative privileges.

Connectivity

Access to Secunia's encrypted servers via SSL (https://psi.secunia.com:443/) and access to Microsoft Windows Update servers,
see also Software Requirements below

Software Requirements

The latest version of Microsoft Update.
You can determine whether or not you are running the latest version by visiting update.microsoft.com.
If you are able to check your system for missing updates through this tool, your system should function properly with the Secunia PSI.

Hardware Requirements:

There are no additional hardware requirements.
If your computer runs any of the above mentioned Operating Systems, then Secunia PSI should work.