Sunday, December 18, 2011

Create your Business Object using SQL Query?

Today I was designing my application and I need to write about 30 classes as the business object layer. As per my design, the business objects in my application are exact replica of my databases table. In order to save time in writing these classes I came up with a tricky logic using SQL server query .I thought of putting in this; in my blog, as it may help some others who needs to do a same exercises.


For your reference please find below a sample of my table ('CountryMaster') in databases

Ignored to write the C# business objects, I used the below query which will gives me the property entry’s for my business objects class.



select 'public '+
case when system_type_id=56 then ' int '+sys.columns.name+' { get; set; }'
when system_type_id=167 then ' string '+sys.columns.name+' { get; set; }'
when system_type_id=239 then ' string '+sys.columns.name+' { get; set; }'
when system_type_id=231 then ' string '+sys.columns.name+' { get; set; }'
when system_type_id=104 then ' string '+sys.columns.name+' { get; set; }'
when system_type_id=61 then ' DateTime '+sys.columns.name+' { get; set; }'
when system_type_id=108 then ' double '+sys.columns.name+' { get; set; }'
when system_type_id=175 then ' string '+sys.columns.name+' { get; set; }'
when system_type_id=34 then ' byte[] '+sys.columns.name+' { get; set; }'
when system_type_id=99 then ' string '+sys.columns.name+' { get; set; }'
end AS 'Class Properties'
from sys.columns
inner join sys.tables on sys.tables.name='CountryMaster'
where sys.columns.object_id=sys.tables.object_id

 
On running the above query will be getting the entry for my business object as below.

Note: the above query may not be complete for all SQL data types, If your databases is having more data types columns, the please add the appropriate c# equal ant code in the case statements.


copy the results from SQL and paste in your C#.net projects in the corresponding class file as  below.

using System;

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

/// Business Objects Class
///

/// Rajesh Kamalakshan
/// 16-12-2011
namespace FiesPackage.Country.BusinessObjects
{
public class Country
{
public int CountryId { get; set; }
public string CountryCode { get; set; }
public string CountryName { get; set; }
public string InBuilt { get; set; }
public int CompanyId { get; set; }
public string Misc { get; set; }
}
}
The highlighted portion has been pasted from the SQL result using the above query.

Friday, December 9, 2011

Type initializer for threw an exception


I thought of sharing this information to others as  it may help someone having the same issues .I have an application which is done in vb .net . It works fine when run from source. This application is a dll bases and it uses crystal report. Everything worked fine with the source.

But the real problem started when I compiled the source to exe and dll .In the compiled version whenever a dll in this application is called form an exe it was throwing an exception as “type initializer for threw an exception”, I googled a lot and found that this issues is due to missing of crystal report files in the clinet machine or Live Pc.

Note: This error can also happed due to some missing files, in my case it was Crystal reports’s supporting files. You can get more details about the missing reference from the stack trace which will be available in the exception.

The solution for this issue was to download and apply the crystal Report redistributable pack, which is relevant for your OS platform where the Application is running. We can get these packs from the below site of crystal report.

http://resources.businessobjects.com/support/additional_downloads/runtime.asp#09

Since my application was compiled in VS 2008, i downloaded the Crystal Reports Basic for Visual Studio .NET 2008

As per the version of crystal report used in your application ,you have to download the respective redistributable package.



Wednesday, November 23, 2011

Reverse percentage calculation?

How to find X, which give you 115000 when 15% is deducted(Reverse Percentage Calculation)?

eg ax + bx = c your eqution is
ax +b = c
where a , b and c are numerical values and x is the unknown!

For the time being we can phrase the equation as

x - 15%x = 115000

then your answer would be

x(1 - 0.15) = 115000 (factorizing x)

x (0.85) = 115000 then dividing by 0.85

x = 135294.1176

substitute for x and you will find this is a correct answer!

135294.1176 - 0.15(135294.1176) = 115000


http://uk.answers.yahoo.com/question/index?qid=20070420010452AAsnX7C

Sunday, November 13, 2011

How to bring jQuery Intellisense in VS 2008

First run the hopfix VS90SP1-KB958502-x86 for VS 2008,you can find the hot fix at


http://archive.msdn.microsoft.com/KB958502/Release/ProjectReleases.aspx?ReleaseId=1736

Open Visual Studio 2008 > File > New > Website > Choose ‘ASP.NET 3.5 website’ from the templates > Choose your language (C# or VB) > Enter the location > Ok. In the Solution Explorer, right click your project > New Folder > rename the folder as ‘Scripts’

Right click the Scripts folder > Add Existing Item > Browse to the path where you downloaded the jQuery library (jquery-1.2.6-vsdoc.js) and the intellisense documentation (jquery-1.2.6-vsdoc.js) > Select the files and click Add.

Now drag and drop the jquery-1.2.6.js file from the Solution Explorer on to your page to create a reference

You can dounload Jquerry intellisense documentation for Vs2008 (jquery-1.2.6-vsdoc.js) at
http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.2.6-vsdoc.js

You can dounload Jquerry jQuery library (jquery-1.2.6-vsdoc.js) at
http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.2.6.js

Note: Since you have applied the hotfix, you do not have to manually add a reference to the jquery-1.2.6-vsdoc.js file in your page. Once the reference to the runtime library has been added, Visual Studio automatically searches for the ‘vsdoc’ file and loads it. You just need to keep both the runtime library and the documentation file next to each other

To test intellisense, add a  script block and key in ‘$(‘. 


More infomrtaion regarding the same can be found at the below loaction

http://weblogs.asp.net/scottgu/archive/2008/11/21/jquery-intellisense-in-vs-2008.aspx
or
http://www.dotnetcurry.com/ShowArticle.aspx?ID=231

Saturday, September 3, 2011

How to select an option in dropdown by its index using JavaScript?

The below code will help you to select an option in a dropdown by its index


You can find more examples of the same in the below website

http://www.mredkj.com/tutorials/tutorial003.html

How to show scroll bars for a label in C# .net?

This functionality can be achieved by using a text box or a rich text box instead of a label


If your are using a Text box then you can achieve the same by below code.


textBox1.AppendText( "Hello World \r\n");

In the above code \r\n is used to print the “Hello World “text in new line each time it is added to the textbox control.

If your are using a Rich Text box then you can archive the same by below code. 

richTextBox1.Text = richTextBox1.Text + "Hellow World \r\n";
richTextBox1.HideSelection = false;
richTextBox1.Focus();
richTextBox1.SelectionStart = richTextBox1.Text.Length;
richTextBox1.ScrollToCaret();

In the above code \r\n is used to print the “Hello World “text in new line each time it is added to the rich textbox control.

Tuesday, August 30, 2011

How to rename the logical name of a database in SQL 2008?

How to rename the logical name of a database in SQL 2008?


The blow TSQL will rename the logical name of your  databases


ALTER DATABASE [yourdatabses]
MODIFY FILE (NAME = 'oldlogicalname', NEWNAME = 'newloggicalname')


In the above example [yourdatabses] can be replaced with your databases name,’oldlogicalname' can be replaced with the existing logical name of your database and 'newloggicalname' name can be replaced with the new logical name for your databases.

Reference
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=54300

How to see the list of files in a SQL server backup file?

How to see the list of files in a SQL server backup file?


Today I was coding one application which will help us to restore and take back of our application’s databases.While coding the application I came across a situation, where I need to now the logical file name of the mdf and ldf files in the backup file.I googled a loot and finally I found a solution which I thought of sharing here for other who needs the same.

The TSQL command below will show the show the back up type and other details of the file.


RESTORE HEADERONLY FROM DISK='E:\xxxxxxxxxxxxx'

 
To retrieve the logical files name and other details use the below TSQL

RESTORE FILELISTONLY FROM DISK = 'E:\xxxxxxxxxxxxx' with file=1

Sunday, August 28, 2011

How to get the machine and windows user name of a logged in user in c#?

The below code will help you to find the Logged in windows user

System.Security.Principal.WindowsIdentity.GetCurrent().Name;

For getting the Machine Name you can use the below code.

WindowsIdentity.GetCurrent().Name;

Sunday, August 14, 2011

HOWTO: Print to a USB Printer from DOS in Windows XP

HOWTO: Print to a USB Printer from DOS in Windows XP

In order to print from DOS in an offline environment like the stores, you will need to do a couple
of things.

1) Install the Microsoft Loopback Adapter
         a) In Control Panel, double click on Add Hardware.
         b) Click Next
         c) When the scan finishes, select "Yes, I have already connected the hardware"
         d) Click Next
         e) Scroll to the bottom of the list and select "Add a new hardware device"
             Click Next
         f) Select "Install the hardware that I manually select from a list (Advanced)"
         g) Click Next
         h) Select "Network Adapters"
         i) Click Next
         j) Select "Microsoft" under the Manufacturer list.
         k) Select "Microsoft Loopback Adapter" in the Network Adapter list.
         l) Click Next
         m) Click Next
         n) Click Finish

2) Configure the Adapter
         a) The loopback adapter is a virtual network adapter and can be configured the same as a
              regular network card.
         b) Set the adapter to have a static IP address such as 192.168.1.1/ 255.255.255.0
         (if this ip already assigned to some other device in your network,then assign a diffrent one) 

3) Share the printer.
         a) I recommend you use a share name that you will remember. I used “Printer” in the new
             machines that are already deployed.

4) Capture the printer port.
         a) NET USE LPT1: \\[Computer Name]\Printer /PERSISTENT:YES





Tuesday, August 9, 2011

An internal error occurred on the report server. See the error log for more details. (rsInternalError) Invalid column name 'AwaitingFirstExecution'.

Today when I resorted our reporstserver databases of SSRS to the newly formatted server I came across the below error as


An internal error occurred on the report server. See the error log for more details. (rsInternalError) Invalid column name 'AwaitingFirstExecution'.

After a lot of googling I found that the above error occurs when there is a difference between version of the reporting server and the report server databases .The solution for this error is as below

1) Stop the reporting server

2) Restore the Reporstserver and ReportServerTempDB databses.

3) Restart reportingsverever.

Saturday, August 6, 2011

How to register a com dll in the context of an administrator user in c#?

The below code sample can be used for registering a com dll from c# by using the regsvr32 command. Normally in a real-time environ the logged in windows ,will not be having enough privileges to carry out the dll registration .In this scenario the code we write should be capable enough to register the dll in some other users context (May be administration) for carrying out the registration process.


The below code registers the dll in the context of administration in order to overcome the privilege issues.


string Adminuser=”Administrator”;
string Password=”Password”;
string Domain=Domainname;
string File=”mydll.dll”;//dll to registrer
System.Diagnostics.ProcessStartInfo ProcessInfo;
ProcessInfo = new System.Diagnostics.ProcessStartInfo();  
ProcessInfo.UserName = @Adminuser;
ProcessInfo.Domain = Domain;
ProcessInfo.Password = SecurePassword;
ProcessInfo.FileName = "regsvr32";
ProcessInfo.UseShellExecute = false;
ProcessInfo.Arguments = File + " /s"; //Here /s is uesr to carring out the
//registration process silently with out showing any message
System.Diagnostics.Process.Start(ProcessInfo);


Hope the above code helps you all.




Happy programing…………………



Friday, August 5, 2011

How to send Crystal Report 7 report as email attachment(excel or pdf)

Today I was asked to find out a solution for sending   crystal report 7 reports in our vb6 application as pdf attachment through outlook. I googled a loot and finally arrive at a solution for the same. I thought it will be good if I share this, so that some others can also get help. The only drawback that I see in this is, as our application using crystal reports 7.Using using crystal reports 7 we will not be able to export to pdf ,so I decided to do the code  to covert the report to excel and attach it to an outlook mail (Programmatically).I also learned after googling that exporting to Pdf pragmatically is not supported if the report is in version 7.PDf exporting is only supported by crystal report from 8.5 onwards.


For achieving these follow the below steps
Open vb6 and open a project.
Add a reference to Crystal report Engine 7 Object Library
Add the controls “Microsoft MAPI Controls 6.0” to the vb6 tool bar
Drag the controls “MAPIMessages” and “MAPISession” to the form.
Add a module and declare the constants as below.

Public Const WS_MINIMIZE = 536870912 ' Make a window of minimum size.
Public Const WS_VISIBLE = 268435456 'Make a window that is visible when it first appears (for overlapping and pop-up windows).
Public Const WS_DISABLED = 134217728 'Make a window that is disabled when it first appears.
Public Const WS_CLIPSIBLINGS = 67108864 'Clip child windows with respect to one another.
Public Const WS_CLIPCHILDREN = 33554432 ' Exclude the area occupied by child windows when drawing inside the parent window.
Public Const WS_MAXIMIZE = 16777216 'Make a window of maximum size.
Public Const WS_CAPTION = 12582912 'Make a window that includes a title bar.
Public Const WS_BORDER = 8388608 'Make a window that includes a border.
Public Const WS_DLGFRAME = 4194304 'Make a window that has a double border but no title.
Public Const WS_VSCROLL = 2097152 'Make a window that includes a vertical scroll bar.
Public Const WS_HSCROLL = 1048576 'Make a window that includes a horizontal scroll bar.
Public Const WS_SYSMENU = 524288 'Include the system menu box.
Public Const WS_THICKFRAME = 262144 ' Include a thick frame that can be used to size the window.
Public Const WS_MINIMIZEBOX = 131072 ' Include the minimize box.
Public Const WS_MAXIMIZEBOX = 65536 ' Include the maximize box.
Public Const CW_USEDFAULT = -32768
'Const CFies_Preview = WS_MAXIMIZE Or WS_CAPTION
Public Const CFies_Preview = WS_MAXIMIZE Or WS_BORDER Or WS_CAPTION Or WS_MAXIMIZEBOX Or WS_MINIMIZEBOX Or WS_SYSMENU Or WS_THICKFRAME




Coming back to the form add controls as shown below and put the below code in respective control and form events.



Private CRPApplication As CRPEAuto.Application 'for reports
Dim crpPrintWindowObj As CRPEAuto.PrintWindowOptions
Private CRPReport As CRPEAuto.Report
Private CRPParameterFieldDefs As CRPEAuto.ParameterFieldDefinitions
Private CRPParameterFieldDef As CRPEAuto.ParameterFieldDefinition
Dim reportname As String


Public Sub WIndowsprint(sendmail As Boolean)
Dim strname As String
strname = "rptchartofaccounts.rpt"
strname = App.Path + "\reports\" + strname
Set CRPApplication = CreateObject("Crystal.CRPE.Application")
CRPApplication.LogOnServer "pdsodbc.dll", "odbcname", "databasename", "username", _
"password" 'ODBC login infomrtaion 
Set CRPReport = CRPApplication.OpenReport(strname)
Set crpPrintWindowObj = CRPReport.PrintWindowOptions
Set CRPParameterFieldDefs = CRPReport.ParameterFields
If sendmail Then
If txtRecepient.Text = "" Then
MsgBox ("Enter recipients it you want yo send this report as a mail")
txtRecepient.SetFocus
Exit Sub
End If
lblStataus.Caption = "Your report is being genereate,Please wait a moment........"
DoEvents
'section for generating report and exporting to excel
Set CrystalOptions = CRPReport.ExportOptions
CrystalOptions.DestinationType = crEDTDiskFile
CrystalOptions.DiskFileName = App.Path + "\Temp\" + reportname + ".xls"
CrystalOptions.FormatType = crEFTExcel50 'cahnge to crEFTPortableDocFormat for pdf, but supported on 'crystal report 8.5 ans above
lblStataus.Caption = "Signing on to your mail software(Outlook)"
CRPReport.Export (False)
' build and send the email and attachment file to outbox
MAPISession1.UserName = ""
MAPISession1.SignOn
thisSessionHandle = MAPISession1.SessionID
MAPIMessages1.SessionID = thisSessionHandle
With MAPIMessages1
.Compose
.RecipType = mapToList
.RecipDisplayName = txtRecepient.Text
.RecipAddress = "SMTP:" + txtRecepient.Text
.MsgSubject = txtSubject.Text
.MsgNoteText = "Body content of your email message "
'this section is for attaching the excel as attachment with the mail
.AttachmentIndex = 0
.AttachmentType = 0
.AttachmentPathName = App.Path + "\Temp\" + reportname + ".xls" '"C:\WINDOWS\TEMP\xxxx.PDF"
.AttachmentPosition = Len(.MsgNoteText) - 1
.AttachmentName = reportname + ".xls"
.Send True 'chnage to false if you want to send the mail with out showing the compose window to user(Directly to outbox)
End With
MAPISession1.SignOff
lblStataus.Caption = ""
Else
With crpPrintWindowObj
.HasExportButton = True
.HasPrintButton = True
.HasPrintSetupButton = True
.HasSearchButton = True
End With
CRPReport.Preview "Contra", 0, 0, CFies_Preview
End If
Exit Sub
End Sub

Private Sub cmdShowReport_Click()
WIndowsprint False
End Sub

Private Sub dmSesndEmail_Click(Index As Integer)
WIndowsprint True
End Sub

Private Sub Form_Load()
reportname = "chartofaccounts"
txtSubject.Text = reportname
End Sub




Monday, August 1, 2011

How to get the current user and Machine from which a query is executed in SQL server?

You can use select host_name() for getting the name of the machine from which the querry has been excecuted and for getting the windows user which excecute the querry tou can use the caommand select SYSTEM_USER

Tuesday, May 10, 2011

Warning: Null value is eliminated by an aggregate or other SET operation

Today when I was executing one of the crystal reports in my application. I came across an error message as “Warning: Null value is eliminated by an aggregate or other SET operation”. I then googled a lot and found that this error is coming when a field is having null values for which an aggregate function like sum,avd etc is executed in the SQL statement.


This error can be suppressed by adding the command as below prior to executing the SQL statement

SET ANSI_WARNINGS OFF

Thursday, April 21, 2011

Loading User Control dynamically in a asp.net webpage

First create user control as in your project ,for reference I am naming it as “WebUserControl.ascx”

Open the aspx page where you want to show the control. Here I am going to show the control when the user clicks on the button on my page. For this first add a reference of the user control “WebUserControl.ascx ‘” as shown below to my aspx page.

Once this is done simply drag a placeholder control from the tool box and add to the aspx page. Also drag a button to the aspx page, so that we can dynamically load the user control on button click.


Once you had added the Placeholder and the button, your aspx page will look as below


Go to the code behind page of you webpage and in the button click event and add the below code


Now run your website and click on the button on the page, you can see that the user control is dynamically loaded to your webpage.