How to Convert Byte Array to String in C#

In .NET, a byte is just a number from 0 to 255 (the numbers that can be represented by eight bits). So, a byte array is just an array of the numbers from 0 to255. At a lower level, an array is a contiguous block of memory, and a byte array is just a representation of that memory in 8-bit blocks.

Let's say you have a Byte[] array loaded from a file and you need to convert it to a String.

1. Encoding's GetString
but you won't be able to get the original bytes back if those bytes have non-ASCII characters

byte[] bytes = { 130, 200, 234, 23 }; // A byte array contains non-ASCII (or non-readable) characters
string Enco = Encoding.UTF8.GetString(bytes); 
byte[] decBytes1 = Encoding.UTF8.GetBytes(Enco);  // decBytes1.Length == 10 !!
// decBytes1 not same as bytes
// Using UTF-8 or other Encoding object will get similar results

2. BitConverter.ToString
The output is a "-" delimited string, but there's no .NET built-in method to convert the string back   to byte array.

string Bitconvo = BitConverter.ToString(bytes);   // 82-C8-EA-17
String[] tempAry = Bitconvo.Split('-');
byte[] decBytes2 = new byte[tempAry.Length];
for (int i = 0; i < tempAry.Length; i++)
    decBytes2[i] = Convert.ToByte(tempAry[i], 16);
// decBytes2 same as bytes

3. Convert.ToBase64String
You can easily convert the output string back to byte array by using Convert.FromBase64String.
Note: The output string could contain '+', '/' and '='. If you want to use the string in a URL, you need to explicitly encode it.

string B64 = Convert.ToBase64String(bytes);  
byte[] decByte3 = Convert.FromBase64String(B64);
// decByte3 same as bytes

4. HttpServerUtility.UrlTokenEncode
You can easily convert the output string back to byte array by using HttpServerUtility.UrlTokenDecode. The output string is already URL friendly! The downside is it needs System.Web assembly if your project is not a web project.

string s3 = Convert.ToBase64String(bytes);  // gsjqFw==
byte[] decByte3 = Convert.FromBase64String(s3);
// decByte3 same as bytes

Credits : combo_ci

Convert Strings to Upper Case in JavaScript

Convert Strings to Upper Case in JavaScript

This will teach you the way to convert strings to upper case in javascript. we will use these if we've a text field needs to capitalized all inputted text or simply the 1st letter of the word.

Source :



Hope you learn from this

How To Make Videos Responsive with CSS

How To Make Videos Responsive with CSS

A responsive website means It will respond to your browser sizes or I can browser stretches. The basic idea of it is to give optimal viewing experience to visitors, nowadays you will rarely see a unresponsive website. If you remember a Jquery snippet I posted about detecting browser real time size It is also responsive. So basically in order to make websites responsive on load you need a meta tag that helps you to stretch/resize the elements of your website but It's not required for this tutorial.

So for this tutorial, only videos with iframe, embed or objects works. You can get the iframe code of any videos from popular websites like YouTube, DailyMotion, Vimeo, MetaCafe etc.

Let's make our style, here's the css we need(if you are a beginner make sure you put the codes within <style>) :

 .Responsive-Video {
    position: relative;
    padding-bottom: 56.25%;
    padding-top: 30px;
    height: 0;
    overflow:
    hidden;
}
   
.Responsive-Video iframe, .Responsive-Video object, .Responsive-Video embed {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}


So after adding the css to your web page, add your video embed code within the div class given below(I know this is NOOB! )  :

<div class="Responsive-Video">

    </div>


Example :

<div class="Responsive-Video">
    <iframe width="760" height="720" src="http://www.youtube.com/embed/Mu4ARzSZOmg" frameborder="0" allowfullscreen></iframe>
    </div>


Screenshot : 

YouTube Responsive Video

If you're using Blogger or Wordpress you can just add the css code within the body and whenever you post a video in your post you can add the embed code within the div class.

How To Make a Line Break/New Line in Java

How To Make a Line Break/New Line in Java
Line Break or New Line : I hope you understand what it is, in HTML you use <br> tag to make a new line so in Java if you want to make a new line it's not that hard but it has several methods depends on the platform.

Coming to the point, most of the java beginners think this is the one and only way to make a new line : System.out.println("\n"); but It's not true.. let me tell you something you might think that whatever you program using java will work on other java supported platforms, YES! they will work on other platforms but there are few things that has to be changed in order to get the functions work.. for example this tutorial; this line of code : System.out.println("\n"); would make a new line only on Windows. As I said before there are few things that are different from platform to platforms.

If you want to make a new line on Mac you must use this : System.out.println("\r"); and for Linux you have to use this : System.out.println("\r\n");. So I came up with something that works on all the platforms, It's pretty simple and works perfectly.

First you need to make a public string and set the value to make a new line(You can also just make normal string and set the value)
Add this line of code before your main event
public static String breakline = System.getProperty("line.separator");

Whenever you need to make a new line just use this line of code 
You can add this wherever you want to
System.out.println(breakline);

Please comment if you have any doubts..!

How To Read A Text File Hosted Online To A String

 How To Read A TXT File Hosted Online To A String
So I got a email asking how to do this, I haven't done this before so went through some Google searches and found how to do this. It was pretty easy. I'll just share the code here maybe it'll be useful for someone.

You need these namespaces :
Imports System.IO
Imports System.Net

Event :
Dim TXT As String = "http://www.ultimateprogrammingtutorials.info/robots.txt"
Dim WC As WebClient = New WebClient()
Dim Read As StreamReader = New StreamReader(WC.OpenRead(TXT))
Dim STR As String = Read.ReadToEnd
TextBox1.Text = STR

  • Replace the TXT string value with your .txt link. 
  • You can also write into a richtextbox or whatever you want(I used textbox1 for example) 
I hope you learned something from this snippet.

How To Draw A Circle Form In C#

 How To Draw A Circle Form In C#
I have seen some controls/components that can change the form into circle.. today I came up with something very simple umm well, it’s done with drawing. You’ll need to add the namespace : using System.Drawing;. We’ll do the drawing in form_load if you want you can do it under a button_click event or something else..

This is the code :

System.Drawing.Drawing2D.GraphicsPath XY = new System.Drawing.Drawing2D.GraphicsPath();
            XY.AddEllipse(0, 0, 300, 300);
            this.Region = new Region(XY);

GraphicsPath() : Initialize a new Graphics Path.
AddEllipse() : Adds a Ellipse to the Graphics Path.
new Region() : Describes a Graphics Shape.

How To Check If Directory Exists In VB.NET And C#

directory in programming
I have had some hard times in solving this problem not these days but sometime ago when I started programming so I think this would be helpful for anyone who has started programming..

Here's the code to check if the directory exists in VB.NET :

Try
            If System.IO.Directory.GetDirectories("PATH").Length > 0 Then
                MsgBox("directory exists")

            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

All you need to do is replace PATH with the directory you want to check... length > 0 identifies if the directory exists.

Here's the code for C# :

try
            {
                if (System.IO.Directory.GetDirectories("PATH").Length > 0)
                {
                    MessageBox.Show("directory exists");

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

Do the same thing as given for VB.NET code.

How To Keep JFrame Always On Top

Always On Top : It’s something that keeps the window on top, you might have seen in some programs they have a menu strip item called Always On Top when you enable it, it will keep the window on top most. You might have seen in Visual Basic or Visual C-Sharp they have a property for that in Form properties so you don’t need to write codes for that but in Java you all know that they neither have a official IDE nor a well advanced 3rd party IDE such as Visual Studio.

Snippet : Using Regular Expressions in Java

This snippet helps you to use Regular Expression(Regex) in Java.

Snippet : Get ASCII Value For Every Characters

This snippet helps you to get the ASCII value for every characters.

Snippet : Detect TOR in PHP

This snippet helps you to detect TOR network connection in PHP

Snippet : Javascript onmouseover and onmouseout

This snippet helps you to make buttons etc.. I have been using this for Download Buttons.

Snippet : Generate Random Password

This snippet helps you to Generate Random Password

Snippet : Base64 Encode and Base64 Decode in PHP

This snippet helps you to encode and decode your text with base64.
Base64 is a group of similar encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The Base64 term originates from a specific MIME content transfer encoding. - Wikipedia

Snippet : TinyURL API in PHP

This snippet helps you to shorten your URLs with TinyURL API(Function with usage)

  1. <?php
  2. function TinyURL($url){
  3.     return file_get_contents('http://tinyurl.com/api-create.php?url='.$url);
  4. }
  5. echo TinyURL('http://www.ultimateprogrammingtutorials.info');
  6. ?>
You need to replace http://www.ultimateprogrammingtutorials.info with the URL you want to shorten

Snippet : HTTP Redirection In PHP

This snippet helps you to redirect to another website/webpage.


  1. <?php
  2.     header('Location: http://www.example.com');
  3. ?>
Replace http://www.example.com with your website URL/webpage URL

Snippet : Detect HTTP User Agent in PHP

The code below helps you to detect the HTTP user agent I mean the browser version.


  1. <?php           
  2.     $useragent = $_SERVER['HTTP_USER_AGENT'];
  3.     echo "<b>User Agent </b>: ".$useragent;
  4. ?>
Return

User Agent : Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.62 Safari/537.36

How To Read And Write Registry In C#

We will see how to read and write registry in c# today .
For people who don't know about registry if i tell it on my own words registry is like a registrar(the person who registers marriage) it registers all the software's that you install so it's like a registrar .


How to read registry ?
Actually reading a registry key is a simple and can be done with 3-4 lines of codes.I am doing this in Graphical User Interface program yes a Windows Forms Project . Add the namespace using Microsoft.Win32; now make sure what you want to read and where you want to read(Local Machine,Current User,etc) , I have no idea what to read so i will read a Google Chrome Extension registered here Google > Chrome > Extensions > dmibjfmphcpfoacbchialfobiohmhged 
How To Read And Write Registry In C#
So as you can see the path in registry now i write 3 lines of codes to read the registry key path(the path of the extension) and show it in a Message Box .
    RegistryKey path = Registry.LocalMachine.OpenSubKey("Software\\Google\\Chrome\\Extensions\\dmibjfmphcpfoacbchialfobiohmhged");//path of the registry
            string read = (string)path.GetValue("path");//creating a string to get the value of 'path'
            MessageBox.Show(read,"Registry Key Value", MessageBoxButtons.OK,MessageBoxIcon.Information);//the messagebox pops with the key 'path' value
I am sorry i couldn't explain everything in the code , as you can see in the first line we define where our key is  "Local Machine" you can put anything places as in your registry for that by the way remember when you read or write registry you should use double // for the destination .

Now when i debug here the Message Box pops up with the 'path' value.
How To Read And Write Registry In C#
Done with reading .

How to write registry?
As it's very easy to read registry , it's easy to write registry by the way i can't write my key into the path i read because it Google's so i chose Current User path to write the registry key. As we did before (reading) add the namespace using Microsoft.Win32; now i will create a registry path and i will add a value called , my whole path is HKEY_CURRENT_USER\Software\Shim\Ultimate_programming_tutorials . ok now i will write the code to write the registry key.
RegistryKey set = Registry.CurrentUser.CreateSubKey("Software\\Shim\\Ultimate_programming_tutorials");//setting the path
            set.SetValue("website", "http://ultimateprogrammingtutorials.blogspot.com");//setting the value
            MessageBox.Show("Value has been added " + set,"Value Added",MessageBoxButtons.OK,MessageBoxIcon.Information);//creating a messagebox to show it's added(value)
            set.Close();//closing the current process
website is the name of the value we are setting and http://ultimateprogrammingtutorials.blogspot.com is the value of work :).

Now when i debug a Message Box pops up saying value has been added and the path that the value was added.
How To Read And Write Registry In C#
Now when i look the path , the value is there .
How To Read And Write Registry In C#
Done with writing :) . I hope this is very useful :)