Saturday, December 28, 2013

Common Table Expressions(CTE)

A common table expression (CTE) is a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement.

Example:
Normal Query

SELECT * FROM  (
        SELECT A.Address, E.Name, E.Age From Address A
        Inner join Employee E on E.EID = A.EID) T
WHERE T.Age > 50
ORDER BY T.NAME

Rewriting the query using CTE expression

With T(Address, Name, Age)  --Column names for Temporary table
AS
(
SELECT A.Address, E.Name, E.Age from Address A
INNER JOIN EMP E ON E.EID = A.EID
)
SELECT * FROM T  --SELECT or USE CTE temporary Table
WHERE T.Age > 50
ORDER BY T.NAME


Ref:

http://www.codeproject.com/Articles/265371/Common-Table-Expressions-CTE-in-SQL-SERVER-2008

http://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx

 

Tuesday, October 29, 2013

How to convert an excel serial date to a .NET date time?


How to convert an excel serial date to a .NET date time?
[ For eg: '29815' to '17/Aug/1981' ]

Use :

DateTime dt = DateTime.FromOADate(29815);
 


Tuesday, October 15, 2013

Upload a file using Web Service

Upload a file using byte array :

Web service method:


  [WebMethod]
        public string UploadFile(byte[] f, string fileName)
        {
            // the byte array argument contains the content of the file and 
            //the string argument contains the name and extension
            try
            {
                MemoryStream ms = new MemoryStream(f);

                //open a file stream pointing the storage folder 'uFiles'

                FileStream fs = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath
                            ("~/uFiles/") + fileName, FileMode.Create);

                // write the memory stream  to the filestream
                ms.WriteTo(fs);
               
                ms.Close();
                fs.Close();
                fs.Dispose();
                return "OK";
            }

            catch (Exception ex)
            {
                     return ex.Message.ToString();
            }
        }


Sample win application code which consumes the method.


 FileInfo fInfo = new FileInfo(<<path & filename>>);

 FileStream fStream = new FileStream(<<path & filename>>,FileMode.Open, FileAccess.Read);

 BinaryReader br = new BinaryReader(fStream);
                 
 // convert the file to a byte array
 byte[] data = br.ReadBytes((int) fInfo.Length);
 br.Close();

localhost.Service1 s = new localhost.Service1();

s.UploadFile(data, <<filename>>);

 fStream.Close();

fStream.Dispose();





Upload an image using web service


Using Base64String:


Soap Web Service Method:-

 [WebMethod]
        public string UploadImage(string imgBase64String, string fname)
        {
            try
            {
                //Converts the base64String to byte array
                byte[] imageBytes = Convert.FromBase64String(imgBase64String);

                //store it in a memory stream
                MemoryStream ms1 = new MemoryStream(imageBytes);

                //generate image from stream
                Image img = Image.FromStream(ms1);

                //Map the folder to store image
                string actFolder = Server.MapPath("~/uFiles/");

                //save the image
                img.Save(actFolder + fname);

                return "OK";
            }
            catch (Exception e)
            {
                return e.Message;
            }

        }



Sample Win application code which consumes above service

// don't forget to add the web reference before using this code. 
//here the reference name is localhost and service name is Service 1 

            string base64;
            using (MemoryStream ms = new MemoryStream())
            {

                Image ximg = Image.FromFile(<<filepath>>);
                ximg.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                base64 = Convert.ToBase64String(ms.ToArray());
               
                localhost.Service1 S1 = new localhost.Service1();

               string r = S1.UploadImage(base64, "MyFile.Jpg");

               MessageBox.Show(r);

            }



Tuesday, September 3, 2013

sqlcmd Utility

Manage SQL Server 2008 Express databases by using the sqlcmd utility from the command prompt.

To Login
Sql Server Authentication
sqlcmd -S server1\SQLExpress -U SqlUserAccount -P SqlPassword

Windows Authentication
sqlcmd -S server1\SQLExpress  -E

FOR DETAILS
http://technet.microsoft.com/en-us/library/ms165702%28v=sql.105%29.aspx

Rebuild System Database (Master.mdf) in SQL Server 2008

  • Open command prompt (Run -> cmd)
  • Change to directory "<<drive>>:\<<installation folder>>\Microsoft SQL Server\100\Setup Bootstrap\Release" (eg:  C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Release)
  • USE THE FOLLOWING COMMAND 
Setup /QUIET /ACTION=REBUILDDATABASE /INSTANCENAME=InstanceName /SQLSYSADMINACCOUNTS=accounts [/ SAPWD= StrongPassword ] [ /SQLCOLLATION=CollationName]

If you have SQL configured for Windows Authentication Mode :

               
setup /ACTION=REBUILDDATABASE /QUIET /INSTANCENAME=<instance name> /SQLSYSADMINACCOUNTS=<accounts>


Eg: setup /ACTION=REBUILDDATABASE /QUIET /INSTANCENAME=SQLEXPRESS /SQLSYSADMINACCOUNTS=mypc\Administrators

If you have SQL configured for Mixed Authentication Mode

 setup /ACTION=REBUILDDATABASE /QUIET /INSTANCENAME=<instance name> /SQLSYSADMINACCOUNTS=<accounts> /SAPWD=<password>

When setup has completed rebuilding the system databases, it will return to the command prompt with no messages

After rebuilding the databases, user instance disabled.
You can enable it either using the command prompt tool named sqlcmd or by using Management Studio.
If using Command tool:

C:\>SQLCmd -S.\sqlexpress -E
1> EXEC sp_configure 'user instances enabled', 1  
2> go  
Configuration option 'user instances enabled' changed from 0 to 1. Run the RECONFIGURE statement to install.  
1> RECONFIGURE  
2> GO  

FOR MORE DETAILS
http://technet.microsoft.com/en-us/library/dd207003%28v=sql.100%29.aspx

http://blogs.msdn.com/b/psssql/archive/2008/08/29/how-to-rebuild-system-databases-in-sql-server-2008.aspx

http://social.msdn.microsoft.com/Forums/sqlserver/en-US/8dabc79b-edef-45fe-a50a-7cf8515c6ed1/how-do-i-run-the-spconfigure-stored-procedure

Thursday, August 8, 2013

STORE IMAGES IN DATABASE



STORE IMAGES IN DATABASE 

‘To show an image in picture box
PictureBox1.Image = Image.FromFile(<<file name with full path>>)

‘To Store an image in database table (sql server)  (In sql server use data type ‘Image’)
Dim picBytes As Byte() = Nothing
Dim memStream As New IO.MemoryStream
PictureBox1.Image.Save(memStream, Drawing.Imaging.ImageFormat.Jpeg)
picBytes = memStream.ToArray()

SqlCmd.CommandText = "Insert Into ImageTable(Picture) Values (@pic)”
SqlCmd.Parameters.AddWithValue("@pic ", picBytes)
SqlCmd.ExecuteNonQuery()

‘To Retrieve an image from sql server database and shown in a Picture box

Dim picBytes As Byte() = CType(DataRow.Item("Picture"), Byte())
Dim memStream As IO.MemoryStream = New IO.MemoryStream(picBytes)
PictureBox1.Image = Image.FromStream(memStream)

Tuesday, June 11, 2013

CRYSTAL REPORTS - SHOW NUMBERS IN WORDS - IN LAKHS & CRORES FORMAT

We can use toWords() Function in crystal reports to show numbers in words. But it does not supports South Asian numbering system (in Lakh & Crore). The following Crystal reports function helps to show amounts in Lakh & Crore.

Create a new formula field and place following script in it.

numbervar pVal:=0;
numbervar Amount:=0;
numbervar frPart:=0;
stringvar InWords :="Rupees ";

Amount := 10000000.75;    [Assign your amount here]

if Amount > 10000000 then pVal := truncate(Amount/10000000);
if Amount = 10000000 then pVal := 1;

   if pVal = 1 then
        InWords := InWords + " " + towords(pVal,0) + " crore"
   else
        if pVal > 1 then InWords := InWords + " " + towords(pVal,0) + " crores";


    Amount := Amount - pVal * 10000000;
    pVal := 0;
    if Amount > 100000 then pVal := truncate(Amount/100000);
    if Amount = 100000 then pVal := 1;
  
   
    if pVal = 1 then
        InWords := InWords + " " + towords(pVal,0) + " lakhs"
    Else
        If pVal > 1 then InWords := InWords + " " + ToWords(pVal,0) + " Lakhs";

        Amount := Amount - pVal * 100000;

        if Amount >= 1 then InWords := InWords + " " + towords(truncate(Amount),0);

        frPart := (Amount - truncate(Amount)) * 100;

        if frPart > 0 then
            InWords := InWords + " and " + towords(frPart,0) + " paisa only"
        else
            InWords := InWords + " only";

ProperCase(InWords)
     


Thursday, June 6, 2013

ERROR - BulletedList and AJAX Toolkit


Error : Generation of designer file failed: The server tag 'asp:BulletedList' is ambiguous....
(if an Ajax Toolkit Manager and a BulletedList placed in same page(.aspx))

Reason: Same "TagPrefix"  'asp' to AJAX toolkit controls and ASP.NET controls

Solution:

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
 TagPrefix="asp" %>
 
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">  
    </asp:ToolkitScriptManager> 
  
//Modify like this.
 
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
TagPrefix="ajx" %>
 

<ajx:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">  
    </ajx:ToolkitScriptManager> 
 
 
 
  

Thursday, May 30, 2013

ERROR :- Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance.

Sql Server 2008 Express Run Under Windows 7.

Connection String:- Data Source=.\SQLEXPRESS; AttachDbFilename= '|DataDirectory|\Database1.mdf'; Integrated Security=True;User Instance=True;Connect Timeout =60


Connection failed with Following Error Message.
"Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance."

Solution
 
1. Stop all user instance processes of SQL Server running under your local account (open up task manager and look for sqlsrv.exe process and end it)

2. Delete all files in the %LOCALAPPDATA%\Microsoft\Microsoft SQL Server Data\SQLEXPRESS folder
(In Windows XP 'C:\Documents and Settings\<<<currentuser>>>\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS)'

3. Restart sql server instance

The problem is known issue.
SQL Express cannot create a user instance using the set of engine files in your local app data folder, deleting them should allow sql server to recreate them with the correct credentials.

Wednesday, May 15, 2013

ENABLE REMOTE CONNECTION IN SQL SERVER AND ENABLE 'sa' ACCOUNT


http://www.linglom.com/it-support/enable-remote-connection-on-sql-server-2008-express/

http://sudeeptaganguly.wordpress.com/2010/04/20/how-to-enable-sa-account-in-sql-server/


ATTACH/DETACH SQL SERVER DATABASE FILE USING COMMAND PROPMT

GO TO 'Start - > Run ->
OPEN  THE TERMINAL [Using Command 'cmd']


sqlcmd -S <server\instance>



USE [master]
GO
CREATE DATABASE [database_name] ON
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Data\<database name>.mdf' ),
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Data\<database name>.ldf' )
 FOR ATTACH ;
GO

---------------------------------------------------------------------------------------------------------
To verify that the database has been attached, type the following two commands:
select name from sys.databases
go
---------------------------------------------------------------------------------------------------------

TO DETACH DB

USE master;
GO
EXEC sp_detach_db @dbname = N'AdventureWorks';
GO



ADD WINDOWS FIREWALL EXCEPTION - SQL SERVER TCP PORT

Note the Sql Server port no.
Start-> Programs-> Microsoft SQL Server 2008 -> Configuration Tools ->SQL Server Configuration Manager

FROM THE TREE VIEW - SELECT Sql Server Network Configuration -> Protocols for 'SQLEXPRESS'
SELECT TCP/IP FROM THE RIGHT PANE
RIGHT CLICK -> PROPERTIES -> IP Address Tab - Note the Dynamic port No

TO ADD EXCEPTION TO WINDOWS FIREWALL
Settings -> Control panel - > Windows Firewall -> Choose Exceptions Tab
Add Port... -> Give a name and specify the port number

[IN WINDOWS 7]
# Add above port in inbound rule and also create another rule - for sqlBrowser.exe

Tuesday, May 7, 2013

To Pass Main Reports Parameter Field Value to Subreport (Crystal Reports)


Step-1 Right click on sub report container in main report, Select -> Edit Sub Report
Step-2 Create the parameter in sub report (if not exists)
Step-3 Return to Main report
Step-4 Right click on sub report container once again and select -> Change sub report links..
Step-5 Select the parameter field (defined in master report) from 'Container Report fields to link'--> Available fields  (shown in left hand side), and add it into 'Fields to Link' list box. Select the newly added field. Select the sub report parameter field name from 'Subreport parameter fields to use' combo box.

DONE..!!!

Friday, March 15, 2013

TO BACKUP SQL SERVER DATABASE USING ADO.NET

Imports System.Data.SqlClient

Public Sub GenerateBackup()
 Using xCon As New SqlConnection(<<ConnectionString>>), _
            Cmd As New SqlCommand
                xCon.Open()
                Cmd.Connection = xCon
                Cmd.CommandText = "BACKUP DATABASE @dbFile TO DISK= @Target WITH FORMAT"
       
        sqlCmd.Parameters.AddWithValue("@dbFile ","<<DatabaseFile>>")
        '//<<DatabaseFile>> -- IF AN ATTACHED DATABASE FILE, SPECIFY THE FULL PATH AND FILE NAME [ie 'C:\MyDbSpace\db.mdf']
                       OTHERWISE SPECIFY THE DATABASE NAME

         sqlCmd.Parameters.AddWithValue("@Target  ","<<BackupFilePath & FileName>>")
                Cmd.ExecuteNonQuery()
                xCon.Close()
End Using

Thursday, March 14, 2013

COMBO BOX DATA BINDING


Public Sub PopulateComboBox(ByRef Combo As ComboBox, ByVal SQl As String)

        Try
            Dim DS As New DataSet
            Dim DA As New SqlClient.SqlDataAdapter
            Dim TableName As String

            TableName = Trim(Mid(SQl, InStr(SQl, " FROM ", CompareMethod.Text) + 6)) & " "
            TableName = Mid(TableName, 1, InStr(TableName, " ", CompareMethod.Text))

            Using xCon As New SqlClient.SqlConnection(conn_string)
                xCon.Open()
                DA.SelectCommand = New SqlClient.SqlCommand(SQl)
                DA.SelectCommand.Connection = xCon
                DA.Fill(DS, TableName)
                xCon.Close()
            End Using
            Combo.DataSource = DS.Tables(TableName)
            Combo.DisplayMember = DS.Tables(TableName).Columns(1).Caption
            Combo.ValueMember = DS.Tables(TableName).Columns(0).Caption
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation)
        End Try

    End Sub


Usage
PopulateComboBox(cmbProperty, "Select Id,Title,SurveyNo From Properties")

To Retrive Value from Combox
cmbProperty.SelectedValue -- to get Id
cmbProperty.SelectedItem -- to get DataRowView -
[Conversion Needed, ie CType(cmbProperty.SelectedItem,DataRowView)]


Set DataGridView Row Height

Dim xRow as DataGridViewRow = DataGridView1.Rows(DataGridView1.Rows.Add())
'//after assigning cell values use following statement
xRow.Height = xRow.GetPreferredHeight(xRow.Index, DataGridViewAutoSizeRowMode.AllCells, False)

Reset SQL Server Database Table's IDENTITY Column


DBCC CHECKIDENT (Table_1, RESEED, 1)

For More Info
http://msdn.microsoft.com/en-us/library/ms176057.aspx


Delegate - Sample -1

'// Assumes  Form-1 shows a list of records and Form2 to create a new record. The purpose of this delegate is to update the list view in Form-1 after saving the record.

FORM-1
Public Class Form1

    Private Sub AddOrUpdateRecordallbackFn(ByVal xRec As AuctionInword)
    //Arg - 'AuctionInword' user defined type
    //METHOD IMPLIMENTATION
    End Sub

   Private Sub Button1_Click()
       '// CALL FORM 2
      Dim xfm As New Form2
      '// Point the function
       xfm.AddOrUpdateAICallBack = AddressOf AddOrUpdateRecordallbackFn
       xfm.Show()
     End Sub

End Class


FORM-2
Public Class Form2
    '//Delegate to Form1 function AddOrUpdateRecordallbackFn
    Public Delegate Sub AddOrUpdateRecord(ByVal xRecord As AuctionInword)   
   
    '//variable to point the function
    Public AddOrUpdateAICallBack As AddOrUpdateRecord

Private Sub SaveRecord()
        //Save record implementation
    Dim _CurrentRecord = New <<User Type>> '//To store new record
    -----------------------
    -----------------------
       
    //After Saving, call the Form1 function 'AddOrUpdateRecordallbackFn' using delegate
    If AddOrUpdateAICallBack IsNot Nothing Then AddOrUpdateAICallBack(_CurrentRecord)
End Sub

End Class

Update a ConnectionString Stored in App.Config File

        using System.Configuration;
        public void updateConnectionString()
        {
           //create a new connection string settings
            ConnectionStringSettings cSetting = new ConnectionStringSettings();

            //connection string
            cSetting.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True;User Instance=True";
            //connection settings name in conf. file
            cSetting.Name = "WindowsFormsApplication1.Properties.Settings.conStr";
            //Provider
            cSetting.ProviderName = "MySql.Data.MySqlClient";

            //get the application conf file
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
           
            //read the connection string section
            ConnectionStringsSection connectionSettings = (ConnectionStringsSection)config.GetSection("connectionStrings");

            //remove the current conf section and add new
            connectionSettings.ConnectionStrings.Remove(cSetting);
            connectionSettings.ConnectionStrings.Add(cSetting);

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);

            //to read and view
            //string newString = ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.conStr"].ConnectionString;
            //System.Diagnostics.Debug.Print(newString);
        }

Wednesday, March 13, 2013

Design Patterns

http://www.dofactory.com/Patterns/Patterns.aspx

Sunday, February 3, 2013

Set Data Directory [.Net Winforms]


  AppDomain.CurrentDomain.SetData("DataDirectory",
            System.Environment.GetFolderPath
           (System.Environment.SpecialFolder.CommonApplicationData))

Insert binary data (ie. images) into SQL Server without front-end application

CREATE TABLE myTable(Document varbinary(max)) 

INSERT INTO myTable(Document) 
SELECT * FROM 
OPENROWSET(BULK N'C:\Image1.jpg', SINGLE_BLOB)