RSS

C# .NET: Converting a string of bits to a byte array

I needed a way to convert a string of bits to a byte array: string -> byte[]

For example take the string 101100110010001111
I need my byte[] to contain: 10001111b (143d), 11001100b (204d), 10b (2d)

I saw a bunch of solutions to this problem in this post but they were either inadequate or too complex for all possible scenarios.

I decided to try to devise my own solution:


        private static byte[] getBitwiseByteArray(string input)
        {
            List<byte> byteList = new List<byte>();
            for (int i = input.Length - 1; i >= 0; i-=8)
            {
                string byteString = "";
                for (int j = 0; (i - j) >= 0 && j < 8; j++)
                {
                    byteString = input[i - j] + byteString;
                }
                if (byteString != "")
                {
                    byteList.Add(Convert.ToByte(byteString, 2));
                }
            }
            return byteList.ToArray();
        }

Let’s take an example (for easy visualization of the logic): 101100110010001111

I need to first extract 8 bits at a time from right to left. Therefore my i iterator counts down from the end of the string to the beginning in sets of 8.

After extracting, I should get 10001111, 11001100, 10

The j iterator ensures that I don’t take more than 8 bits at a time. It also ensures that when there are less than 8 bits left in the string (as in the case of 10 where only 2 bits were left), I stop extracting at that stage.

byteString contains at most 8 bits and is ready to be converted to a byte type using the Convert.ToByte function with the binary format specified.

 
1 Comment

Posted by on July 8, 2011 in .NET Framework Development, C#

 

Tags: , , , , , , , , , , ,

C# .NET: Reading and writing to MS Excel 2007 where multiple tables are in the same worksheet

I wasn’t able to find a neat solution anywhere online to this: I have multiple tables on the same worksheet and I want to be able to interact with each of these tables from Visual Studio in C#.

By putting together ideas from various places I came up with my own solution, which I hope you find to be elegant.

As I intended to use the Access Database Engine, I had to download it from here. Although I’m running an x64 OS, I have an x32 office instance running and therefore I was forced to install the x32 Access Database Engine.

1) Define names for your tables in Excel. Select only the table (header row included, title row excluded), and in the Formulas tab click on Define Names. Give it a name (you will be using this as the table name later).

Also make sure none of your column names have spaces in them.

2) In your Visual Studio project, go to Project->Add Reference and add System.Data.Linq

I would recommend that you use a connection string in the following manner:

@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + fileName + ";Extended Properties=Excel 12.0 Xml"

This piece of code will read the values from the Excel file:

using System;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Data.OleDb;

namespace ExcelInteractionProgram
{
    [Table(Name = "Student")]
    class Student
    {
        private double _Id;
        [Column(Storage = "_Id")]
        public double Id
        {
            get
            {
                return this._Id;
            }
            set
            {
                _Id = value;
            }
        }
        
        private string _Name;
        [Column(Storage="_Name")]
        public string Name
        {
            get
            {
                return this._Name;
            }
            set
            {
                _Name = value;
            }
        }

        private DateTime _DateOfJoining;
        [Column(Storage = "_DateOfJoining")]
        public DateTime DateOfJoining
        {
            get
            {
                return this._DateOfJoining;
            }
            set
            {
                _DateOfJoining = value;
            }
        }
    }

    [Table(Name = "ExamScore")]
    class ExamScore
    {
        private double _StudentId;
        [Column(Storage = "_StudentId")]
        public double StudentId
        {
            get
            {
                return this._StudentId;
            }
            set
            {
                _StudentId = value;
            }
        }

        private double _Score;
        [Column(Storage = "_Score")]
        public double Score
        {
            get
            {
                return this._Score;
            }
            set
            {
                _Score = value;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string fileName = @"C:\Student.xlsx";
            DataContext db = new DataContext(new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + fileName + ";Extended Properties=Excel 12.0"));
            
            Table<Student> students = db.GetTable<Student>();
            Table<ExamScore> examScores = db.GetTable<ExamScore>();
            
            // Attach the log to show generated SQL.
            db.Log = Console.Out;

            var dbQuery =
                from student in students
                join score in examScores
                    on student.Id equals score.StudentId
                select new { student.Id, student.Name, student.DateOfJoining, score.Score };

            foreach (var row in dbQuery)
            {
                Console.WriteLine("Student Id = {0}; Name={1}; Date of Joining={2}; Score={3}", 
                    row.Id, row.Name, row.DateOfJoining.ToShortDateString(), row.Score);
            }

            Console.ReadKey();
        }
    }
}

If you’re getting errors, these pointers might help:

1) I got: Specified cast is not valid.

when my Student Id property was defined as an integer:

        private int _Id;
        [Column(Storage = "_Id")]
        public int Id
        {
            get
            {
                return this._Id;
            }
            set
            {
                _Id = value;
            }
        }     

In Excel, all numbers are stored as double type by default so you must use double for the property as well.

2) I got: No value given for one or more required parameters.

when I named the property different from the name of the column.

As an example I have called the property ‘Score1′ instead of ‘Score’:

	private double _Score;
        [Column(Storage = "_Score")]
        public double Score1
        {
            get
            {
                return this._Score;
            }
            set
            {
                _Score = value;
            }
        }

3) I got: The Microsoft Access database engine could not find the object ‘Student’. Make sure the object exists and that you spell its name and the path name correctly. If ‘Student’ is not a local object, check your network connection or contact the server administrator.

when I misspelled my file name in the connection string.

Eg: Student1.xlsx instead of Student.xlsx. Note that the error is misleading because you would think you made a mistake in naming the Student table within the Excel worksheet but in my case, it was the file name which had the typo.

 
Leave a comment

Posted by on May 10, 2011 in .NET Framework Development, C#

 

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

ASP.NET 4.0: Integrating Membership Roles into the Registration process of the CreateUserWizard

This post assumes you have an ASP.NET project with Membership providers set up. If you’re having trouble with this, you can refer to my previous post.

In my project, I have User Roles and Admin Roles. User Roles are low privilege roles that allow users to interact with the server application. For example if you create an application for a gym management system, you can define “Trainer” and “Trainee” as User Roles. When a trainer or trainee would like to create an account on the portal, he can choose what type of account he wants. Different roles will offer a different webpage with different features. The key here is to ensure that these two roles are not necessarily privileges. They are merely for the system to distinguish between different types of users.

Only users can be added via the CreateUserWizard. Admins, and Roles can be added and modified via the ASP.NET Web Site Configuration Tool. Roles are classified as User Roles or Admin Roles in their “Description” attribute which is a default column in the Roles table (and which I filled up with “User Role” or “Admin Role” directly using SQL Server Management Studio).

When a user registers via the CreateUserWizard, he should be able to choose his role which can only be of type User Role. Therefore I look through the Roles table and filter Roles whose “Description” is “User Role” and populate these in a drop-down list.

The default CreateUserWizard in the new ASP.NET web application project created by Visual Studio 2010 has two steps: Sign Up for Your New Account & Completed.

I want a user to be able to choose his User Role in the Sign Up for Your New Account Step.

1) In design view click on the tag to open Tasks dialog and choose Edit Templates. This shows you the CreateUzerWizard in the edit templates mode. Find the tag again and open the Tasks dialog and choose “Content Template” under Sign Up for Your New Account in the “Display” dropdown list.

2) Click on the point where you want the Roles options to be inserted and hit “Enter” to create a new ‘p’ tag. Add a “Role: ” label whose AssociatedControlID is “RoleList”, to be defined later.

3) Drag and drop an SqlDataSource there. In the tag, click on Configure Data Source. Choose the database (or the connection string to the database) that has already been configured through Aspnet_regsql.

4) Select “Specify columns from a table or view”. I chose vw_aspnet_Roles. I also opened the Where dialog as shown below.

5) Drag and drop a DropDownList at the desired location and call it “RoleList”. Click on its tag and choose Data Source as the one defined in steps 3 and 4. I chose RoleName for both Data Text Field and Data Value Field.

Now we can test the appearance of the form by opening the website and going to the Registration page and seeing the CreateUserWizard. It works for me- I see my DropDownList and it shows me my available User Roles.

6) Finally we need to customize the RegisterUser_CreatedUser method in Register.aspx.cs to ensure that Roles are updated in the database when the CreateUserButton is pressed.

This can be done with 2 simple lines of code. The first line identifies the RoleList DropDownList in the control hierarchy. The second line retrieves the selected role name from the DropDownList and updates the database.

        protected void RegisterUser_CreatedUser(object sender, EventArgs e)
        {
            FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);
            DropDownList RoleList = RegisterUserWizardStep.ContentTemplateContainer.FindControl("RoleList") as DropDownList;
            Roles.AddUserToRole(RegisterUser.UserName, RoleList.SelectedValue);
            string continueUrl = RegisterUser.ContinueDestinationPageUrl;
            if (String.IsNullOrEmpty(continueUrl))
            {
                continueUrl = "~/";
            }
            Response.Redirect(continueUrl);
        }
 
Leave a comment

Posted by on May 3, 2011 in .NET Framework Development, ASP.NET

 

Tags: , , , , , , , , , , , , , , , , ,

C# .NET: Inheritance and type casting between parent class objects and child class objects

I needed a recap on inheritance concepts in C# as I am designing a complex software system after a long time.

I also needed to test out the typecasting features of the language so I decided to write a program to try out different things. The ‘as’ and ‘in’ keywords give me some powerful functionality which I will surely use later on.

There are no syntax errors in this program

using System;
using System.Collections.Generic;
using System.Reflection;

namespace InheritanceTest
{
    internal class Circle
    {
        int radius;
        public Circle(int radius)
        {
            this.radius = radius;
        }

        public int Radius
        {
            get { return radius; }
        }

        public double Area
        {
            get { return Math.PI * Math.Pow(radius, 2); }
        }
    }

    internal class Cylinder: Circle
    {
        int height;
        public Cylinder(int radius, int height): base(radius)
        {
            this.height = height;
        }

        public int Height
        {
            get { return height; }
        }

        public double Volume
        {
            get { return Area * height; }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List circles = new List();
            circles.Add(new Cylinder(4, 5));
            circles.Add(new Cylinder(6, 10));
            foreach (Cylinder cylinder in circles)
            {
                Console.WriteLine("Radius: {0}; Height: {1}; Volume: {2}", cylinder.Radius.ToString("f2"), cylinder.Height.ToString("f2"), cylinder.Volume.ToString("f2"));
            }

            //circles[0]. only gives me access to circle properties
            //(Cylinder)circles[0]. only gives me access to circle properties
            //(circles[0] as Cylinder). gives me access to circle & cylinder properties

            //However the type of the above 3 all seem to be Cylinder even though the first two only give me access to Circle properties
            Console.WriteLine("Type of circles[0]: " + circles[0].GetType().Name);
            Console.WriteLine("Type of (Cylinder)circles[0]: " + circles[0].GetType().Name);
            Console.WriteLine("Type of circles[0] as Cylinder: " + (circles[0] as Cylinder).GetType().Name);

            Console.ReadKey();
        }
    }
}

Output:

Radius: 4.00; Height: 5.00; Volume: 251.33
Radius: 6.00; Height: 10.00; Volume: 1130.97
Type of circles[0]: Cylinder
Type of (Cylinder)circles[0]: Cylinder
Type of circles[0] as Cylinder: Cylinder

When casting reference types or objects, the pointer to the original object is still held by the object. A true copy is not created.

 
Leave a comment

Posted by on April 28, 2011 in .NET Framework Development, C#

 

Tags: , , , , , , , , , ,

 
Follow

Get every new post delivered to your Inbox.