MP3 Informer - Get Lyrics, Album Art, Artist Image, Album Name and Release Date

15. May 2010 01:13

C# Projects 

I am a huge music fan, so huge that I need headphone while I work on my machine and if I don't have them in my head I can't work.Cool It's not the case with me but most of the people do the same thing. But sometimes the things get worsts when people with their headphones on start singing.Laughing Ok they sing only when they know the lyrics and if they won't they search for them and then sing along. It's not the case with me but for the folks who wants to search lyrics for their songs collection, I have created this small tool which will help them to get lyrics, get album name, album art, release date and artist image. Just enter artist name and song name and let this tool get the details for you. I have consumed lyricWIKI, Last.FM and LyricFly web service to get the details.

This tool is build on .NET Framework 3.5. So in order to use this tool you must have .NET 3.5 Framework installed on your machine.

Download: MP3 Informer.msi (655.00 kb)

 

 No Rating

How To Find Whether The Machine Is of 32-Bit/64-Bit Architecture

13. May 2010 22:22

.NET Framework C# Code Snippets 

The easiest way to find out the processor architecture is to use the Environment class GetEnvironmentVariable method

Console.WriteLine(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"));

This will print the processor architecture on the console window i.e. x86 and x64 for 32-bit and 64-bit respectively.

Currently rated 5.0 by 1 person

Using SQL CLR Stored Procedure To Track IP Address

24. April 2010 00:24

C# SQL Server T-SQL 

Recently I was asked by one of my friend how to call a web service directly from a stored procedure. He needs to track IP addresses using a stored procedures so, I suggested him two ways to call a web service using the SQL Procedure.

  • Using SP_OACREATE with MSXML
  • Create an assembly using SQL CLR using C#.

I personally tried using the first way to call a web service but was not successful. Then I learnt about SQL CLR programming with Visual Studio and C# and get it done in a first go. As a good friend I create the whole project for my friend. And if your thinking that this is going to be a difficult, this is not so.

To start creating a project, open Visual Studio and create a new project.

Before the project gets loaded completely, you will be asked to add database reference. Here select the database you want to build the assembly for. If you don’t want to add a database reference then just simply cancel. But if you choose the reference to add at this point then this would really be of help as this will allow you to deploy your assembly directly to the SQL Server database but if you have not then you need to write some SQL scripts.

NOTE: If you have added a database reference then it doesn’t mean that your assembly is build specifically for that database you can still deploy your assembly in other database also.

As I am creating a stored procedure, I then have to add a New Item to my project. Right-click project choose Add>Stored Procedure.  Here give a name of your choice to stored procedure. In my case it is IPInfo.

Change the static method here to accept a parameter. Our parameter will be an IP address, which I have set as of string type.

public static void GetIPInfo(string IP)
{  
//Do something here
}

Now the question here is from where we can the information of the IP Addresses? I do some search and found a website http://www.geobytes.com. It offers some rich information of the IP Address you want to track, so out of five sources I choose to go with geobytes.

Lets take a quick look at the code. This is not a web service as you can see from the code below, I am just making a http request and then get the response in an XML form so I can easily traverse the nodes and read/save the information I received.

string XMLResponse;
IPAddress = IP;
byte[] XMLResults;
string str = "http://www.geobytes.com/IpLocator.htm?GetLocation&template=xml.txt"
+ "&IpAddress=" + IP;
XMLResults = new WebClient().DownloadData(str.ToString());
XMLResponse = Encoding.UTF8.GetString(XMLResults);

Note the fourth line where I have built the URL. The parameter Template should always have a value to xml.txt. If you change the name, it won’t throw any error but the data received cannot be read and saved in a database table. Convert the response to string format and then read the nodes one by one using the below code.

try
        {
            XmlDocument document = new XmlDocument();
            document.LoadXml(XMLResponse);
            XmlNode documentElement = document.DocumentElement;
            if (documentElement.HasChildNodes)
            {
                for (int i = 0; i < documentElement.ChildNodes.Count; i++)
                {
                    if (documentElement.ChildNodes[i].NodeType == XmlNodeType.Element)
                    {
                        switch (documentElement.ChildNodes[i].Name)
                        {
                            case "locationcode":
                                LocationCode = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "fips":
                                FIPS104 = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "iso2":
                                ISO2 = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "iso3":
                                ISO3 = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "ison":
                                ISON = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "internet":
                                Internet = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "countryid":
                                CountryID = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "country":
                                Country = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "regionid":
                                RegionID = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "region":
                                Region = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "code":
                                RegionCode = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "adm":
                                Admn1Code = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "cityid":
                                CityID = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "city":
                                City = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "latitude":
                                Latitude = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "longitude":
                                Longitude = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "timezone":
                                TimeZone = documentElement.ChildNodes[i].InnerText;
                                break;

                            case "certainty":
                                Certainty = documentElement.ChildNodes[i].InnerText;
                                break;
                        }
                    }
                }
            }
        }
        catch (Exception) { }

I traversed through each node and save the response data in a variable I have already declared in my program using a switch case. Once all the response has been assigned to the variable save the response to the database.

try
        {
            using (SqlConnection con = new SqlConnection("context connection=true"))
            {
                string strSQL = "INSERT INTO IPTrack values ('" + IPAddress + "','" + LocationCode + "','" + FIPS104 + "','" + ISO2 + "','" + ISO3 + "','" + ISON + "','" + Internet + "','" + CountryID + "','" + Country +
                    "','" + RegionID + "','" + Region + "','" + RegionCode + "','" + Admn1Code + "','" + CityID + "','" + City + "','" + Latitude + "','" + Longitude + "','" + TimeZone + "','" + Certainty + "')";
                SqlCommand cmd = new SqlCommand(strSQL, con);
                //SqlContext.Pipe.ExecuteAndSend(cmd);
                con.Open();
                SqlContext.Pipe.ExecuteAndSend(cmd);
                //cmd.ExecuteNonQuery();
            }
        }
        catch (Exception) { }
    }

Build you project and you will see a DLL file in your debug/release folder. But this will not work. You will still have to set some permission level to assembly and to SQL Server database.

Set Assembly Permissions

Before you build the final version of the assembly go the project properties and set the permissions as shown below.

Under Build select option for Generate Serialization Assembly to On.

Under Database select Permission Level to Unsafe

SQL Server Permissions

If you find problems while deploying your assembly, then make sure you have CLR enabled and set the Trustworthy property for the database to ON.

You can find all the scripts in the attached solution below.

Deploying your assembly

To deploy your assembly use the below SQL command:

CREATE ASSEMBLY IPTracker from 'C:\IPInfo.dll' WITH PERMISSION_SET = EXTERNAL_ACCESS
GO

To create a stored procedure whcih in trun calls the SQL method from the deployed assembly:

CREATE PROC TrackIP(@IP as nvarchar(50))AS 
-- [Assembly Name].[Class Name].[CLR function Name]
EXTERNAL NAME IPTracker.StoredProcedures.GetIPInfo 
GO

And execute the procedure to get the IP information

Download: IPInfo.zip (19.46 kb)

Currently rated 5.0 by 1 person

Windows 7 Development: Creating Jumplist In Windows 7

28. March 2010 02:08

API C# Windows 

I am quite fascinated with Windows 7 before even I get it started using it. Actually I have just started on a fun project for my personal use which includes jump list. Why I am doing this? To navigate and get access to the application and internet addresses I need anytime. I am tired of typing addresses and navigating to the programs I frequently use. I have just started so I thought I must blog about my jump list experience with you all. You won't believe but I am still using Visual Studio 2008 with .NETFX 3.5. Ok, Let's talk about some Windows development. In my last post on Windows 7 development I explain how can you have Aero effects for your Windows applications. If you haven't read my post on Aero effects in Windows Application then you should have a look at this.

Windows 7 API Code Pack comes packed up with some serious development stuff for Windows 7. If you don't have it yet then check my post for Windows 7 Development resources.

We all know and view the new taskbar in Windows 7 and when your program got pinned in the taskbar you can simply left click to run your program or right-click to view more options associated with your program. To make it more clear I give you an example. I use Winsnap (a tool to take screenshots with dropshadows) to take screenshots and yes I use it quite frequently, so I pinned it to my taskbar.

That's the third icon from the Windows start button. When I click it normally it opens up the Winsnap application and show me the panel from where I can take and make settings for my next screenshot. but when I right-click the pinned Winsnap icon on my taskbar it show me the same basic settings which I will be using if I would have launched the application.

Now when I have to take screenshots with my utility I just right-click Winsnap icon pinned to my taskbar and I am done. The items that you see under the heading Tasks is having all your jump list items. It is indeed possible to have some common functions from your application to be included in the jump list or can have some external links for applications like calculator, notepad, paint etc. If you don't know (just in case) if you can pin something on the taskbar then you can also unpin it.

I hope now I am quite clear with jump list in Windows 7. So lets gets our hands on developing an application with jump list.

 

Getting Started

Start it up creating a simple windows forms application with a name of your choice. As we are delaing with Windows 7 API we need to have it added in our project references. Files you need to add to references are:

  • Microsoft.WindowsAPICodePack.DLL
  • Microsoft.WindowsAPICodePack.Shell.DLL

You can have these API libraries once you donwlod the API code pack. After you are done adding the required references, you can switch to the code window and do the rest of the work.

Creating Jump List

Start up with adding the namespace:

using Microsoft.WindowsAPICodePack.Taskbar;
using Microsoft.WindowsAPICodePack.Shell;

Create a jump list by calling CreateJumpList method, which is a part of Microsoft.WindowsAPICodePack.Taskbar.JumpList namespace.

JumpList list = JumpList.CreateJumpList();

If you want to show the most recent files you have used, then you can do that by using this line of code:

list.KnownCategoryToDisplay = JumpListKnownCategoryType.Recent;

JumpListKnownCategoryType is an enumeration which will let you accomplish this. You can also have some other available options.

  • Frequent: Display the frequent known category.
  • Neither: Don't display either known category. You must have atleast one user task and or custom category link in order to not see the default 'Recent' known category.
  • Recent: Display the recent known category.

To add some commonly used applications to the jump list then you can have it with in less than a jiffy. Create a JumpListLink class object and associate it with the JumpList class object. I use notepad a lot to note down my work, now I want to add to the jump list and I code it this way:

JumpList list = JumpList.CreateJumpList();
string SysPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System),
"notepad.exe");
JumpListLink JLink = new JumpListLink(SysPath,"Notepad.exe");
list.AddUserTasks(JLink);
list.Refresh();

One line of code can be used to include icon for your program. The IconReference property will let you add the icon the jump list item. Set the default value to '0', if you want to use the default icon for the application.

JumpList list = JumpList.CreateJumpList();
string SysPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System),
"notepad.exe");
JumpListLink JLink = new JumpListLink(SysPath,"Notepad.exe");
JLink.IconReference = new IconReference(SysPath, 0);
list.AddUserTasks(JLink);

You will now have a new jump list item. If you want to have your applications and links to be categorised in the jump list, then you can have custom jump list catgory and categorize your jump list items accordingly.

JumpList list = JumpList.CreateJumpList();
string SysPath = System.IO.Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.System),"notepad.exe");
JumpListLink JLink = new JumpListLink(SysPath,"Notepad.exe");
list.AddUserTasks(JLink);
JumpListCustomCategory jcc = new JumpListCustomCategory("My Programs"); 
jcc.AddJumpListItems(new JumpListLink("http://www.microsoft.com", "Microsoft")); list.AddCustomCategories(jcc);
list.Refresh();

Categorizing programs is bit easy this way. I can categorize web URLs, my favourites programs and some other places/links on my computer. There is lot more you can do with Jump Lists. I hope the explaination above can let you create your own applications with jump lists.

 

 

 

Currently rated 5.0 by 2 people

Passing Parameters and Loading Crystal Report Programmatically

1. March 2010 11:55

C# SQL Server 

Reporting is an important part for every application. Crystal reports are widely used and also available in Visual Studio for reporting purposes. I personally never like designing application interfaces and working on web designs, it needs good designing skills which I lack and so I never put my hands on designing anything, but sometimes we have to. In crystal reports when you create a report using wizard or just adding a blank report to the project and then fetching data using code (after designing), the report works fine on the machine where you have designed and develop it and the problem occurs when you have to deploy or distribute your application with reports on multiple machines or clients. Of course, the connection string or you can say in simple words the server name, database name, user name and password is different than the name you used in your connection string while you test and make your application ready to be distributed. Therefore, to overcome this problem I wrote a class which will help me to achieve this in one line and also keep my code neat and clean. So this simple class will let you set the connection for your report dataset and let your reports work properly without any problems.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;


namespace ReportExportDemo
{
    class Reports
    {
        static TableLogOnInfo crTableLogonInfo;
        static ConnectionInfo crConnectionInfo;
        static Tables crTables;
        static Database crDatabase;

        public static void ReportLogin(ReportDocument crDoc, string Server, string Database, string UserID, string Password)
        {
            crConnectionInfo = new ConnectionInfo();
            crConnectionInfo.ServerName = Server;
            crConnectionInfo.DatabaseName = Database;
            crConnectionInfo.UserID = UserID;
            crConnectionInfo.Password = Password;
            crDatabase = crDoc.Database;
            crTables = crDatabase.Tables;
            foreach (CrystalDecisions.CrystalReports.Engine.Table crTable in crTables)
            {
                crTableLogonInfo = crTable.LogOnInfo;
                crTableLogonInfo.ConnectionInfo = crConnectionInfo;
                crTable.ApplyLogOnInfo(crTableLogonInfo);
            }
        }

        public static void ReportLogin(ReportDocument crDoc, string Server, string Database)
        {
            crConnectionInfo = new ConnectionInfo();
            crConnectionInfo.ServerName = Server;
            crConnectionInfo.DatabaseName = Database;
            crConnectionInfo.IntegratedSecurity = true;
            crDatabase = crDoc.Database;
            crTables = crDatabase.Tables;
            foreach (CrystalDecisions.CrystalReports.Engine.Table crTable in crTables)
            {
                crTableLogonInfo = crTable.LogOnInfo;
                crTableLogonInfo.ConnectionInfo = crConnectionInfo;
                crTable.ApplyLogOnInfo(crTableLogonInfo);
            }
        }
    }
}

This class contains ReportLogIn method which is overloaded which lets you choose the type of datasourde you want to connect to. The first method in the class requires SQL Server authentication to log-on to the server and the second method is used when the server is configured on windows authentication, similar to Integrated Security = true.

Sample usage of the Reports class is as follows. I have used AdventureWorks database for this example. If you dont have adventure works database then you can download the sample database from Microsoft's website or from codeplex or you can create your own report and check it with this example.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;


namespace ReportExportDemo
{
    public partial class frm_main : Form
    {
        public frm_main()
        {
            InitializeComponent();
        }

        private void btn_prvrpt_Click(object sender, EventArgs e)
        {
            int Cust_Id = Convert.ToInt32(txt_customerid.Text);
            //string Cust_Id = txt_customerid.Text.Trim();

            //Initialize report document object and load the report in the report document object
            ReportDocument crReportDocument = new ReportDocument();
            crReportDocument.Load(Application.StartupPath+"\\Reports\\AdventureCustReport.rpt");
            
            //login to the server to get details from the server and populate to the report           
            Reports.ReportLogin(crReportDocument, "MX\\SERVER", "AdventureWorks", "sa", "pass#w0rd1");
            
            //Pass parameter to the report object
            crReportDocument.SetParameterValue("id", Cust_Id);

            //To create PDF from the crystal report
            crReportDocument.ExportToDisk(ExportFormatType.PortableDocFormat, "CustomerReport" + Cust_Id + ".pdf");
            
            //Preview the generated PDF
            System.Diagnostics.Process.Start(Application.StartupPath + "\\CustomerReport" + Cust_Id + ".pdf");
        }
    }
}

Note the namespaces I have used in the above code and also how I have used the Reports class ReportLogin method. For more clarification of the code download the sample application with the report below.

One important thing that you have to keep in mind while designing report is to set the parameter. After you have set the parameter and you use your report with the above code, the report will then populate the whole lot of records in the table trrespective of the parameter you pass to the report. So to avoid this and to view only the record of your choice you needs to set the formula in the crystal report. the formula goes like this:

Sample Syntax:

{<Table's Column Name>}={?<Parameter Name>}

In my report this formula looks something like this:

{CustomerID}={?ID}

Download: ReportExportDemo.zip (55.76 kb)

Currently rated 3.5 by 2 people