Thursday, June 30, 2016

What is an identity in SQL Server?

//SQL Server Auto-Increment Primary Key Field
//Example
CREATE TABLE [dbo].[DEMO]
(
SrNo [int] IDENTITY(1,1) NOT NULL,
)

auto-increment primary key field

Friday, June 24, 2016

MonthName and Month Number List between Two Date in SQL Server

//Month Name and Month Number List between Two Date in SQL Server

SELECT  MONTH(DATEADD(MONTH, x.number, '2013-05-31'))[MonthNo],
DATENAME(MONTH, DATEADD(MONTH, x.number,  '2013-05-31'))[Month],
DATENAME(YEAR, DATEADD(MONTH, x.number,  '2013-05-31'))[Year] ,
LEFT(DATENAME(MONTH, DATEADD(MONTH, x.number,  '2013-05-31')),3) + ' ' + DATENAME(YEAR, DATEADD(MONTH, x.number,  '2013-05-31')) [Name]
FROM    master.dbo.spt_values x
WHERE   x.type = 'P'      
AND     x.number <= DATEDIFF(MONTH,  '2013-05-31',  '2014-05-31')


Month Name List in SQL Server

//Month Name List in SQL Server

SELECT number,
DATENAME(MONTH, CAST(year(getdate()) as varchar(4)) +'-' + CAST(number as varchar(2)) + '-1') monthname

FROM master..spt_values
WHERE Type = 'P' and number between 1 and 12
ORDER BY Number




Find Month Name to Month number in SQL Server

//Current Month Name and Month number Find in SQL Server

SELECT MONTH(LEFT(DATENAME(MONTH,Getdate()),15) + ' 1 2016') Number ,(DATENAME(MONTH,Getdate())) MonthName

OutPut :-


Saturday, June 18, 2016

Add Table Valued Parameters in SQL Server

//Table-Valued Parameters In SQL Server

//Table Data Pass to another Same Table

--Frist Create User Define Table Type

EX.
create type T_Demo as Table
(
Field Name DataType
)

//C# Code to Pass Sql Server
SqlCommand _LocalCommnad = new SqlCommand();

  SqlConnection LocalCon = new SqlConnection("Data Source=.\sql2012;Initial Catalog=demo;User ID=sa;Password=123;Persist Security Info = false;");
 
                        if (LocalCon.State == ConnectionState.Open)
                                {
                             
                                    _LocalCommnad.Connection = LocalCon;
                                    _LocalCommnad.CommandType = CommandType.StoredProcedure;
                                    _LocalCommnad.CommandText = "SP_DEMO";
                                    _LocalCommnad.Parameters.Clear();

                                    _LocalCommnad.Parameters.AddWithValue("Table", _dt);
                                    _LocalCommnad.CommandTimeout = 0;
                                    _LocalCommnad.ExecuteNonQuery();
                             
                                }
                            _LocalCommnad.Connection = null;
                        LocalCon.Close();


==============================================================
//Update Flg in Table

Create proc [dbo].[SP_DEMO] (  @Table T_Demo  READONLY  )
as begin
update  Demo set Trf=1,TrfDate=Getdate()
from Demo
  inner join  @Table  as TT on   TT.INVNO=BILLH.INVNO  and TT.TrfDate=BILLH.TrfDate
End


Sunday, June 12, 2016

C#.Net Async and await Attribute used (C# 5)

//Async / await, caller information attributes

using System;
using System.IO;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
// Create task and start it.
// ... Wait for it to complete.
Task task = new Task(ProcessDataAsync);
task.Start();
task.Wait();
Console.ReadLine();
    }

    static async void ProcessDataAsync()
    {
// Start the HandleFile method.
Task<int> task = HandleFileAsync("C:\\1.txt");

// Control returns here before HandleFileAsync returns.
// ... Prompt the user.
Console.WriteLine("Please wait patiently " +
   "while I do something important.");

// Wait for the HandleFile task to complete.
// ... Display its results.
int x = await task;
Console.WriteLine("Count: " + x);
    }

    static async Task<int> HandleFileAsync(string file)
    {
Console.WriteLine("HandleFile Enter");
int count = 0;

// Read in the specified file.
// ... Use async StreamReader method.
using (StreamReader reader = new StreamReader(file))
{
   string v = await reader.ReadToEndAsync();

   // ... Process the file data somehow.
   count += v.Length;

   // ... A slow-running computation.
   //     Dummy code.
   for (int i = 0; i < 10000; i++)
   {
int x = v.GetHashCode();
if (x == 0)
{
   count--;
}
   }
}
Console.WriteLine("HandleFile Exit");
return count;
    }
}

Output: initial

HandleFile Enter
Please wait patiently while I do something important.

Output: final

HandleFile Enter
Please wait patiently while I do something important.
HandleFile Exit

Count: 1916146

Thursday, June 9, 2016

Auto property initializer easy in C#.net (6.0)

Auto property initializer easy in C#.net (6.0) Example
public class Name
    {
     
        public string FirstName { get; set; } = "ABC";
        public string LastName { get; } = "XYZ";
    }

Wednesday, June 8, 2016

REVERSE Keyword in SQL Server

//REVERSE

select REVERSE ('abc123')


O/P:=  321cba

While Statement in SQL Server

//While loop in SQL Server

CREATE PROCEDURE [dbo].[prc_while]
AS
begin
DECLARE @@i NUMERIC;
DECLARE @@Alfa VARCHAR(max);
SET @@Alfa = '';
SET @@i = 65;
WHILE @@i <=90
BEGIN
SET @@Alfa =@@Alfa+  CHAR(@@i)
SET @@i = @@i +1;
PRINT @@Alfa;
END
END


O/P:=

A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
ABCDEFGH
ABCDEFGHI
ABCDEFGHIJ
ABCDEFGHIJK
ABCDEFGHIJKL
ABCDEFGHIJKLM
ABCDEFGHIJKLMN
ABCDEFGHIJKLMNO
ABCDEFGHIJKLMNOP
ABCDEFGHIJKLMNOPQ
ABCDEFGHIJKLMNOPQR
ABCDEFGHIJKLMNOPQRS
ABCDEFGHIJKLMNOPQRST
ABCDEFGHIJKLMNOPQRSTU
ABCDEFGHIJKLMNOPQRSTUV
ABCDEFGHIJKLMNOPQRSTUVW
ABCDEFGHIJKLMNOPQRSTUVWX
ABCDEFGHIJKLMNOPQRSTUVWXY
ABCDEFGHIJKLMNOPQRSTUVWXYZ

TableNameWithRecordCount in SQL Server

TableNameWithRecordCount
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

exec Sp_TableNameWithRecordCount 'backup'

CREATE PROC [dbo].[Sp_TableNameWithRecordCount]
@DatabaseName varchar(50)
AS
begin
declare @@Query varchar(max)
set @@Query = '
SELECT
    t.NAME AS TableName,
    SUM(p.rows) AS [RowCount]
FROM ['+
  @DatabaseName+'].sys.tables t
INNER JOIN [' +  
   @DatabaseName+'].sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
   ['+
  @DatabaseName+'].sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
WHERE
    i.index_id <= 1
GROUP BY
    t.NAME, i.object_id, i.index_id, i.name
    HAVING SUM(p.rows) > 0
ORDER BY
    tablename'
print @@Query
exec(@@Query)
end

Over To Ball Calculator in SQL Server

//Over To Ball Calculator
//use to cricket
Create PROCEDURE [dbo].[Sp_OverToBall] @over VARCHAR(50)
AS
  BEGIN
      SET nocount ON;

      DECLARE @@Over INT
      DECLARE @@Bal NUMERIC(18, 2)
      DECLARE @@SubBal INT
      DECLARE @@SubOver INT

      IF( Charindex('.', @over) != 0 )
        BEGIN
            SET @@Bal= Substring(@over, Charindex('.', @over) + 1, Len(@over))
            SET @@Over = Substring(@over, 0, Charindex('.', @over))
        END
      ELSE
        BEGIN
            SET @@Bal= 0
            SET @@Over = @over
        END

      IF( @@Bal > 6 )
        BEGIN
            SET @@SubBal = @@Bal % 6
            SET @@SubOver = ( @@Bal - @@SubBal ) / 6
        END
      ELSE
        BEGIN
            SET @@SubBal = @@Bal
        END

      SELECT Isnull(@@Over, 0) + Isnull(@@SubOver, 0) [Over],
             Isnull(@@SubBal, 0) Ball,
             Isnull(@@SubBal, 0) + ((Isnull(@@Over,0) + Isnull(@@SubOver, 0))* 6 )TotalBall
  END



-----O/P:=
Over  Ball  TotalBall
20         0       120

Dynamic DataType in C#.Net

//C#.Net (Version 5) Used

   dynamic b = 5;
    b = b + "abc";
    MessageBox.Show(b);


OUTPUT :=  5abc

using sealed class in C#.Net

//sealed Class Simple Example
class A {}
sealed class B : A {}

--Sealed methods

class X
{
 protected virtual void First() { }
 protected virtual void Second() { }
}
class Y : X
{
 sealed protected override void First() {}
 protected override void Second() { }
}

Tuesday, June 7, 2016

Value Type Parameter in C#.net

//Value Type Paramete Used C#.net
using System;

namespace ValueType
{
  class Program
   {
     public static int qube(int num)
      {
        return num * num * num;
      }
     static void Main(string[] args)
      {
        int val,number;
        number = 5;
        //Passing the copy value of number variable
        val = Program.qube(number);
        Console.Write(val);
        Console.ReadLine();
      }
   }
}

O/P:= 125

Monday, June 6, 2016

C#.Net in Crystal Report Not Run

//Crystal Report Not Run Then Config File Add This Line

<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>

 <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
  </startup>

Backup Database in Sql Server

//Database Backup
create PROCEDURE [dbo].[sp_BackupDatabases]
            @databaseName sysname = '',
            @backupType CHAR(1) = 'F',
            @backupLocation nvarchar(200)  = '\d:\',
    @Out Int Output
AS
 begin
       SET NOCOUNT ON;
         Begin Try

            DECLARE @DBs TABLE
            (
                  ID int IDENTITY PRIMARY KEY,
                  DBNAME nvarchar(500)
            )
       
             -- Pick out only databases which are online in case ALL databases are chosen to be backed up
             -- If specific database is chosen to be backed up only pick that out from @DBs
            INSERT INTO @DBs (DBNAME)
            SELECT Name FROM master.sys.databases
            where state=0
            AND name=@DatabaseName
            OR @DatabaseName IS NULL
            ORDER BY Name
         
            -- Filter out databases which do not need to backed up
            IF @backupType='F'
                  BEGIN
                  DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','AdventureWorks','master','ReportServer','ReportServerTempDB','msdb','model')
                  END
            ELSE IF @backupType='D'
                  BEGIN
                  DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks','ReportServer','ReportServerTempDB','msdb','model')
                  END
            ELSE IF @backupType='L'
                  BEGIN
                  DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks','ReportServer','ReportServerTempDB','msdb','model')
                  END
            ELSE
                  BEGIN
                  RETURN
                  END
         
            -- Declare variables
            DECLARE @BackupName varchar(100)
            DECLARE @BackupFile varchar(100)
            DECLARE @DBNAME varchar(300)
            DECLARE @sqlCommand NVARCHAR(1000)
            DECLARE @dateTime NVARCHAR(20)
            DECLARE @Loop int                
                     
            -- Loop through the databases one by one
            SELECT @Loop = min(ID) FROM @DBs

      WHILE @Loop IS NOT NULL
      BEGIN

-- Database Names have to be in [dbname] format since some have - or _ in their name
      SET @DBNAME = '['+(SELECT DBNAME FROM @DBs WHERE ID = @Loop)+']'

-- Set the current date and time n yyyyhhmmss format
      SET @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),101),'/','') + '_' +  REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','')

-- Create backup filename in path\filename.extension format for full,diff and log backups
      IF @backupType = 'F'
            SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_FULL_'+ @dateTime+ '.BAK'
      ELSE IF @backupType = 'D'
            SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_DIFF_'+ @dateTime+ '.BAK'
      ELSE IF @backupType = 'L'
            SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_LOG_'+ @dateTime+ '.TRN'

-- Provide the backup a name for storing in the media
      IF @backupType = 'F'
            SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' full backup for '+ @dateTime
      IF @backupType = 'D'
            SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' differential backup for '+ @dateTime
      IF @backupType = 'L'
            SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' log backup for '+ @dateTime
 PRINT  'chiman -'+@BackupName;
-- Generate the dynamic SQL command to be executed

       IF @backupType = 'F'
                  BEGIN
               SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
                  END
       IF @backupType = 'D'
                  BEGIN
               SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH DIFFERENTIAL, INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'      
                  END
       IF @backupType = 'L'
                  BEGIN
               SET @sqlCommand = 'BACKUP LOG ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'      
                  END

-- Execute the generated SQL command
       EXEC(@sqlCommand)
 PRINT @sqlCommand;
-- Goto the next database
SELECT @Loop = min(ID) FROM @DBs where ID>@Loop

END

Set @Out=0
  End Try

   Begin Catch
 Set @Out=999
 End Catch
 END

Run This :=
exec [dbo].[sp_BackupDatabases]  null, 'F',  'D:\',0

GetMonthListBetweenTwoDate in SQL Server

//MonthListBetweenTwoDate in SQL Server
CREATE PROCEDURE [dbo].[Get_MonthListBetweenTwoDate]
AS
BEGIN

DECLARE @StartDate  DATETIME,
        @EndDate    DATETIME;

SET @StartDate = '2013-05-31'      
SET @EndDate   = '2014-05-30';



SELECT DATENAME(MONTH, DATEADD(MONTH, x.number, @StartDate))[Month],DATENAME(YEAR, DATEADD(MONTH, x.number, @StartDate))[Year]
FROM    master.dbo.spt_values x
WHERE   x.type = 'P'      
AND     x.number <= DATEDIFF(MONTH, @StartDate, @EndDate)
end



DeleteAllTableData in SQL Server

//Delete All Table
Create PROCEDURE [dbo].[DeleteAllTableData]
AS
    BEGIN
 
        EXEC sp_MSForEachTable 'DISABLE TRIGGER ALL ON ?'
        EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
        EXEC sp_MSForEachTable 'DELETE FROM ?'
        EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
        EXEC sp_MSForEachTable 'ENABLE TRIGGER ALL ON ?'
     
    END

ViewDependency in SQL Server

//Dependency in Table
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SP_ViewDependency]
@TableName varchar(50),
@Database VARCHAR(50)

AS
begin
DECLARE @@Query VARCHAR(max)
SET @@Query =
'SELECT DISTINCT o.name
    FROM '+ @Database +'.dbo.sysobjects o
    INNER JOIN ' + @Database+'.dbo.syscomments c ON c.Id = o.Id
    WHERE category = 0 AND c.text like ''%' + @TableName + '%''
    ORDER BY o.name '
    PRINT @@Query
    EXEC (@@Query)
end

FieldDepencencies in SQL Server

//FieldDepencencies in SQL Server
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[SP_FieldDepencencies]
@DataBaseName varchar(50),
@TableName varchar(50),
@FieldName varchar(50)

as
begin
declare @@Query varchar(max)
set @@Query = 'use '+@DataBaseName

set @@Query =@@Query+' select distinct name
from syscomments c
join sysobjects o on c.id = o.id
where TEXT like ''%'+@TableName+'%'' and TEXT like ''%'+@FieldName+'%'''
print @@Query
Exec (@@Query)
end

use Sequences in SQL Server

//sequences used in version(12) Example
CREATE TABLE dbo.Contacts (
        ContactId int IDENTITY(1,1) NOT NULL,
        FirstName varchar(60),
        LastName varchar(60),
        Phone varchar(60)
);

INSERT INTO dbo.Contacts
SELECT name, name, name
FROM master.dbo.spt_values;

-- Skip 300 rows 'into' the results and
-- take the next 10 records:
SELECT ContactId, FirstName, LastName, Phone
FROM dbo.Contacts
ORDER BY ContactId
        OFFSET 0 ROWS
        FETCH NEXT 10 ROWS ONLY;



CHOOSE Keyword In SQL Server

//CHOOSE In SQL Server
SELECT CHOOSE(2, '1','2', 'Unknown')
AS [No];

O/P= 2
==========================================
SELECT CHOOSE(4,'1','2','Unknown') AS [x];

O/P= NULL

Property Assign easily in C#.net.

 public string FirstName { get; set; }

use lazy in C#.Net

//lazy used in C#.net
using System;

class Test
{
    int[] _array;
    public Test()
    {
Console.WriteLine("Test()");
_array = new int[9];
    }
    public int Length
    {
get
{
   return _array.Length;
}
    }
}

class Program
{
    static void Main()
    {

Lazy<Test> lazy = new Lazy<Test>();


Console.WriteLine("IsValueCreated = {0}", lazy.IsValueCreated);


Test test = lazy.Value;


Console.WriteLine("IsValueCreated = {0}", lazy.IsValueCreated);

// The object can be used.
Console.WriteLine("Length = {0}", test.Length);
    }
}

====================================================

Output

IsValueCreated = False
Test()
IsValueCreated = True
Length = 10

Send Email in Java

// File Name SendFileEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendFileToEmail
{
   public static void main(String [] args)
   {
     
      // Recipient's email ID needs to be mentioned.
      String to = "abcd@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Create the message part
         BodyPart messageBodyPart = new MimeBodyPart();

         // Fill the message
         messageBodyPart.setText("This is message body");
       
         // Create a multipar message
         Multipart multipart = new MimeMultipart();

         // Set text message part
         multipart.addBodyPart(messageBodyPart);

         // Part two is attachment
         messageBodyPart = new MimeBodyPart();
         String filename = "file.txt";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename);
         multipart.addBodyPart(messageBodyPart);

         // Send the complete message parts
         message.setContent(multipart );

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Serializing an Object in Java

import java.io.*;

public class Serialize
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Abc";
      e.address = "india";
      e.SSN = 123;
      e.number = 101;
     
      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("/tmp/employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
}

Use of Indexers in C#.net

//C#.net Indexers
using System;
namespace IndexerApp
{
   class IndexedNames
   {
      private string[] namelist = new string[size];
      static public int size = 10;
      public IndexedNames()
      {
         for (int i = 0; i < size; i++)
         namelist[i] = "N";
      }
   
      public string this[int index]
      {
         get
         {
            string tmp;
       
            if( index >= 0 && index <= size-1 )
            {
               tmp = namelist[index];
            }
            else
            {
               tmp = "";
            }
         
            return ( tmp );
         }
         set
         {
            if( index >= 0 && index <= size-1 )
            {
               namelist[index] = value;
            }
         }
      }
   
      static void Main(string[] args)
      {
         IndexedNames names = new IndexedNames();
         names[0] = "Zara";
         names[1] = "Riz";
         names[2] = "Nuha";
         names[3] = "Asif";
         names[4] = "Davinder";
         names[5] = "Sunil";
         names[6] = "Rubic";
         for ( int i = 0; i < IndexedNames.size; i++ )
         {
            Console.WriteLine(names[i]);
         }
       
         Console.ReadKey();
      }
   }
}

===============================================

O/P:=
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N
N
N

Saturday, June 4, 2016

[Solved] KB3102429 causes Crystal Report export to PDF to failed


  • Crystal Report Export to PDF to Fail



  1. Windows 10


1.Go to Start, enter View Installed Updates in the Search Windows box, and then press Enter.
2.In the list of updates, locate and then select update KB3102429, and then select Uninstall.


  1. Windows 8 and Windows 8.1


1.Swipe in from the right edge of the screen, and then select Search. If you’re using a mouse, point to the lower-right corner of the screen, and then select Search.

2.Enter windows update, select Windows Update, and then select Installed Updates.

3.In the list of updates, locate and then select update KB3102429, and then select Uninstall.


  1. Windows 7, Windows Vista and Windows XP


1.Go to Start, enter Run, and then select Run.

2.Enter Appwiz.cpl, and then select OK.

3.Use one of the following procedures, depending on the operating system that you’re running.

3.1.Windows 7 and Windows Vista
3.1.1.Select View installed updates.
3.1.2In the list of updates, locate and select update KB3102429, and then select Uninstall.

3.2.Windows XP
3.2.1.Select the Show updates check box.
3.2.1In the list of updates, locate and select update KB3102429, and then select Remove.

queries to manage hierarchical or parent-child relational rows in SQL Server

//queries to manage hierarchical or parent-child relational rows Example
WITH q AS
(
SELECT *
FROM MKT1
WHERE ParentID =4
UNION ALL
SELECT m.*
FROM MKT1 m
JOIN q
ON m.parentID = q.PersonID

)
SELECT *
FROM q WHERE 1=1

Writing an Anonymous Method in C#.Net

//Anonymous Method in C#.Net
using System;

delegate void NumberChanger(int n);
namespace DelegateAppl
{
   class TestDelegate
   {
      static int num = 10;
      public static void AddNum(int p)
      {
         num += p;
         Console.WriteLine("Named Method: {0}", num);
      }
   
      public static void MultNum(int q)
      {
         num *= q;
         Console.WriteLine("Named Method: {0}", num);
      }
   
      public static int getNum()
      {
         return num;
      }
      static void Main(string[] args)
      {
         //create delegate instances using anonymous method
         NumberChanger nc = delegate(int x)
         {
            Console.WriteLine("Anonymous Method: {0}", x);
         };
       
         //calling the delegate using the anonymous method
         nc(10);
       
         //instantiating the delegate using the named methods
         nc =  new NumberChanger(AddNum);
       
         //calling the delegate using the named methods
         nc(5);
       
         //instantiating the delegate using another named methods
         nc =  new NumberChanger(MultNum);
       
         //calling the delegate using the named methods
         nc(2);
         Console.ReadKey();
      }
   }
}

====================================================================

O/P:=

Anonymous Method: 10
Named Method: 15
Named Method: 30

Use Enum in C#.net

//Enum used in C#.net
using System;
namespace EnumApplication
{
   class EnumProgram
   {
      enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

      static void Main(string[] args)
      {
         int WeekdayStart = (int)Days.Mon;
         int WeekdayEnd = (int)Days.Fri;
         Console.WriteLine("Monday: {0}", WeekdayStart);
         Console.WriteLine("Friday: {0}", WeekdayEnd);
         Console.ReadKey();
      }
   }
}



O/P:=

Monday: 1
Friday: 5

Remove Error in Team Viewer Commercial Use Suspected

Step:-

1> First Close Teamviewer, if it is running.

2> Click on Start –> Run –> type %appdata% –> delete TeamViewer folder

3> Delete registry folder: hkcu/software/teamviewer

4> Delete registry folder: hklm/software/teamviewer

5> Change the MAC Address of your LAN card,

You Can DownLoad MAC Address Changer Form Follow Link :

http://www.download.com/SMAC-MAC-Address-Changer/3000-2085_4-10536535.html?tag=mncol&cdlPid=10796334

6> Restart your Teamviewer and you should get a new ID and also should solve the 'Commercial Use Suspected' problem

Get Date List From Selected Month in SQL Server

//Date List Month Wise
//StartDate Input and EndDate Input

DECLARE @Date DATE='03/15/2016'
DECLARE @startDate DATE=CAST(MONTH(@Date) AS VARCHAR) + '/' + '01/' + + CAST(YEAR(@Date) AS VARCHAR) -- mm/dd/yyyy
DECLARE @endDate DATE=DATEADD(DAY,-1,DATEADD(MONTH,1,@startDate))

SELECT [Date] = DATEADD(Day,Number,@startDate)
FROM master..spt_values
WHERE Type='P'
AND DATEADD(day,Number,@startDate) <= @endDate


=====================================================================

O/P:=

Date
2016-03-01
2016-03-02
2016-03-03
2016-03-04
2016-03-05
2016-03-06
2016-03-07
2016-03-08
2016-03-09
2016-03-10
2016-03-11
2016-03-12
2016-03-13
2016-03-14
2016-03-15
2016-03-16
2016-03-17
2016-03-18
2016-03-19
2016-03-20
2016-03-21
2016-03-22
2016-03-23
2016-03-24
2016-03-25
2016-03-26
2016-03-27
2016-03-28
2016-03-29
2016-03-30
2016-03-31

Solution for Sendkey Permission Denied For Vb.6.0

//Sendkey Permission Denied For Vb.6.0

Public Sub sendkeys_New (text As Variant, Optional wait As Boolean = False)
Dim WshShell As Object
Set WshShell = CreateObject('wscript.shell')
WshShell.Sendkeys CStr(text), wait
Set WshShell = Nothing
End Sub



Example :

sendkeys_New  '{TAB}'

Friday, June 3, 2016

Multiple Inheritance in C#

//Multiple
using System;
namespace InheritanceApplication
{
   class Shape
   {
      public void setWidth(int w)
      {
         width = w;
      }
      public void setHeight(int h)
      {
         height = h;
      }
      protected int width;
      protected int height;
   }

   // Base class PaintCost
   public interface PaintCost
   {
      int getCost(int area);

   }
 
   // Derived class
   class Rectangle : Shape, PaintCost
   {
      public int getArea()
      {
         return (width * height);
      }
      public int getCost(int area)
      {
         return area * 70;
      }
   }
   class RectangleTester
   {
      static void Main(string[] args)
      {
         Rectangle Rect = new Rectangle();
         int area;
         Rect.setWidth(5);
         Rect.setHeight(7);
         area = Rect.getArea();
       
         // Print the area of the object.
         Console.WriteLine("Total area: {0}",  Rect.getArea());
         Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area));
         Console.ReadKey();
      }
   }
}

Delegates in C#.net

//Delegate
using System;

delegate int NumberChanger(int n);
namespace DelegateAppl
{
   class TestDelegate
   {
      static int num = 10;
      public static int AddNum(int p)
      {
         num += p;
         return num;
      }

      public static int MultNum(int q)
      {
         num *= q;
         return num;
      }
      public static int getNum()
      {
         return num;
      }

      static void Main(string[] args)
      {
         //create delegate instances
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);
       
         //calling the methods using the delegate objects
         nc1(25);
         Console.WriteLine("Value of Num: {0}", getNum());
         nc2(5);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}

SHUTDOWN YOUR OTHER PC

//SHUTDOWN YOUR OTHER PC
Shutdown ur friend’s computer when everytime it startsThats really easy.put this followin text in a .reg file and run it in the victims pc:Windows Registry Editor Version 5.00[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]”VIRUS”=”%windir%\\SYSTEM32\\SHUTDOWN.EXE -t 1 -c \”Howz this new Virus ah\” -f”DONT PUT IT IN UR COMPUTER,I AM NOT RESPONSIBLE, if it happens, to you, start windows in safe mode, and open registry editor by typiing REGEDIT in start->run. navigate to [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]and remove the string value named VIRUS, restart you computer

difference between Database Mail and SQLMail

//Database Mail and SQLMail
Database mail is newly introduced concept in SQL Server 2005 and it is replacement of SQLMail of SQL Server earlier version. Database Mail has many enhancement over SQLMail. Database Mail is based on SMTP (Simple Mail Transfer Protocol) and also very fast and reliable where as SQLMail is based on MAPI (Messaging Application Programming Interface). Database mail depends on Service Broker so this service must be enabled for Database Mail. Database Mail can be encrypted for additional security. SQLMail is lesser secure as it can encrypt the message as well anybody can use SMTP to send email. Additionally, for MAPI to be enabled for SQLMail it will require Outlook to be installed. All this leads to potential security threat to database server.

Find Form Name In VB6.0 File ( *.VBP) File

‘ Take 3 List Box in Your Form and  1 command Button




Private Sub Command1_Click()
‘ Enter Your Project FileName
TransferProjectDetails (“TEST.vbp”)
End Sub


Public Function TransferProjectDetails(ProjectVbpFile As String) As Boolean
Dim ln As Integer ‘ for lineno
Dim opos As Integer ‘for opening position
‘On Error GoTo errlbl
TransferProjectDetails = False
Dim TextLine
If Len(ProjectVbpFile) = 0 Then
    ProjectVbpFile = “\project1.vbp”
Else
    ProjectVbpFile = “\” & ProjectVbpFile
End If
Open App.Path & ProjectVbpFile For Input As #1 ‘ Open file.
Open App.Path & “\ProjectFileDetails.txt” For Output As #2 ‘ Open file.
Do While Not EOF(1) ‘ Loop until end of file.
ln = ln + 1
Line Input #1, TextLine ‘ Read line into variable.
Debug.Print ln & ” ” & TextLine ‘ Print to the Immediate window.


If InStr(1, TextLine, “Sub”) > 0 Then
    opos = ln
    Print #2, ln & ” ” & TextLine ‘TextLine
ElseIf InStr(1, TextLine, “Form=”) = 1 Then
    ” = 1 means it gets only forms filenames. not name of the forms name property
    Print #2, ln & ” ” & TextLine
    fname = Right(TextLine, Len(TextLine) – (InStr(TextLine, “=”)))
    List1.AddItem fname
ElseIf InStr(1, TextLine, “Module=”) = 1 Then
    Print #2, ln & ” ” & TextLine
    Mfname = Right(TextLine, Len(TextLine) – (InStr(TextLine, “;”)))
    List2.AddItem Mfname
    ‘print #2,
ElseIf InStr(1, TextLine, “Class=”) > 0 Then
    Print #2, ln & ” ” & TextLine
    Cfname = Right(TextLine, Len(TextLine) – (InStr(TextLine, “;”)))
    List3.AddItem Trim(Cfname)
    ‘print #2,
End If
Loop
Close #1 ‘ Close file.
Close #2
TransferProjectDetails = True
Exit Function
errlbl:
MsgBox Err.Description
TransferProjectDetails = False


End Function

Value List Bind in UltraWinGrid

//UltraWinGrid
private void UltGrdEmpMast_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            ValueList vl;
            if (!e.Layout.ValueLists.Exists(“MyValueList”))
            {
                vl = e.Layout.ValueLists.Add(“MyValueList”);
                vl.ValueListItems.Add(1, “A”);
                vl.ValueListItems.Add(2, “B”);
                vl.ValueListItems.Add(3, “C”);
            }
            e.Layout.Bands[0].Columns[“Emp_Name”].ValueList = e.Layout.ValueLists[“MyValueList”];
        }

Remove VbCrlf Value In String From Starting Or End

Private Function RemoveVbCrlf(StrText As String) As String
    If Right$(StrText, 2) = vbCrLf Then
        RemoveVbCrlf = Left$(StrText, Len(StrText) – 2)
        StrText = Left$(StrText, Len(StrText) – 2)
    End If
   
    If Left$(StrText, 2) = vbCrLf Then
        RemoveVbCrlf = Right$(StrText, Len(StrText) – 2)
    End If
   
    If Len(RemoveVbCrlf) = 0 Then
        RemoveVbCrlf = StrText
    End If
End Function

Using Grouping function With Cube in Sql Server

//Cube used
SELECT
CASE WHEN GROUPING(customername) = 1 THEN ‘All Customer’ ELSE customername END CustomerName,
CASE WHEN GROUPING(itemname) = 1 THEN ‘All Items’ ELSE itemname END ItemName,
SUM(Quantity*PricePerCase)
FROM orders
GROUP BY customername,itemname
WITH Cube

Using Grouping function With Rollup in Sql Server

//Rollup Used
SELECT
 CASE WHEN GROUPING(customername) = 1 THEN ‘All Customer’ ELSE customername END CustomerName,
 CASE WHEN GROUPING(itemname) = 1 THEN ‘All Items’ ELSE itemname END ItemName,
 SUM(Quantity*PricePerCase)
FROM orders
GROUP BY customername,itemname
WITH ROLLUP

Clear TextBox In Vb 6.0 less Code

//All Clear Teaxbox in vb6.0 less Code
Public Sub ClearText(ByRef SRC_FORM As Form)

On Error Resume Next

Dim Control As Control

For Each Control In SRC_FORM.Controls

If (TypeOf Control Is TextBox) Then Control = vbNullString

Next Control

Set Control = Nothing

End Sub

Find Mismatch Table in Different Database

Select name from sys.objects Where type_desc=’USER_TABLE’

except

Select name from sys.objects Where type_desc=’USER_TABLE’

Find Column Mismatch in Different Database

//Except
//Table1 Not Mactch Value Display

SELECT TABLE_NAME,COLUMN_NAME

FROM GCLV.INFORMATION_SCHEMA.COLUMNS a

except

SELECT TABLE_NAME,COLUMN_NAME

FROM INFORMATION_SCHEMA.COLUMNS a

(-)Round Function in Vb 6.00

//(-)Round Function in Vb 6.00
If You Want To Round in last 2 digit Exm. 151 = 200        And  149 = 100 Round1(Value,-2)

Private Function Round1(DouAmt As Double, IntDegit As Integer) As Double

IntDegit = Abs(IntDegit)

DouAmt = Round(DouAmt)

If IntDegit = 0 Then

Round1 = DouAmt

Exit Function

End If



If Right(DouAmt, IntDegit) < Val('5' + String(IntDegit - 1, '0')) Then

Round1 = (DouAmt - Right(DouAmt, IntDegit))

Else

Round1 = (DouAmt - Right(DouAmt, IntDegit)) + Val('10' + String(IntDegit - 1, '0'))

End If

End Function
End Function

Find dates And Week Numbers Between To Dates in SQL Server

//dates And Week Numbers Between To Dates
declare @date_from datetime, @date_to datetime
set @date_from = '07/01/2015'
set @date_to = '07/31/2015';

with dates as(
select @date_from as dt
union all
select DATEADD(d,1,dt) from dates where dt<@date_to
)

select datepart(day, datediff(day, 0, dt)/7 * 7)/7 + 1 WeekNo,* from dates

use merge statement SQL Server

//Merge Statement in version(12)

MERGE B AS TARGET
USING A AS SOURCE
ON
(
TARGET.Y_Code=SOURCE.Y_CODE AND TARGET.PROC_CODE=SOURCE.PROC_CODE
)
WHEN MATCHED
THEN
UPDATE
SET
TARGET.Y_CODE=Source.Y_CODE,
TARGET.PROC_CODE=Source.PROC_CODE,
TARGET.L_CODE=Source.L_CODE,
TARGET.L_CARAT=Source.L_CARAT,
TARGET.TYP=Source.TYP
WHEN NOT MATCHED BY TARGET
THEN
INSERT (
[Y_CODE],
[PROC_CODE],
[L_CODE],
[L_CARAT],
[TYP]
)
VALUES
(
Source.Y_CODE,
Source.PROC_CODE,
Source.L_CODE,
Source.L_CARAT,
Source.TYP
);

Select *from a
Select *from b

Attach database With connection string used to SQL Server

//Attach database With connection string used to SQL Server

Provider=SQLNCLI10;Server=.\SQLExpress;
AttachDbFilename=|DataDirectory|mydb.mdf;Database=dbname;
Trusted_Connection=Yes;

kill all current connections to a SQL Server database

ALTER DATABASE YourDatabase SET MULTI_USER

recover Database from Restoring mode

//Restore Database
RESTORE DATABASE Databasename WITH RECOVERY

How to create directory (Folder ) using SOL Server?

//Create Folder in SQLServer command

declare @Path varchar(100)
set @Path = 'c:\test'
EXEC master.dbo.xp_create_subdir @Path

get last backup time of database in Sql server

//Last backupTime Query
SELECT sdb.Name AS DatabaseName,
ISNULL(CONVERT(VARCHAR(214),MAX(bus.backup_finish_date)),’-‘) AS LastBackUpTime
FROM sys.sysdatabases sdb
LEFT OUTER JOIN msdb.dbo.backupset bus ON bus.database_name = sdb.name
GROUP BY sdb.Name

Get Set Property Pass By Table Name in SQL Server and easy to Property declare in C#.net

     CRATE PROCEDURE [dbo].[Sp_GetClsClass] @TableName VARCHAR(50)
AS
    BEGIN
 
 
        SELECT  CHAR(13) + 'private '
                + CASE WHEN a.DATA_TYPE = 'varchar' THEN 'string'
                       WHEN a.DATA_TYPE = 'numeric' OR a.DATA_TYPE = 'smallint' THEN CASE WHEN a.Numeric_scale != 0 THEN 'double' ELSE 'int' END
                       WHEN a.DATA_TYPE = 'datetime' THEN 'string'
                       WHEN a.data_type = 'bit' THEN 'int'
                       ELSE a.DATA_TYPE
                  END + ' _' + a.COLUMN_NAME + ';' + CHAR(13) + 'public '
                + CASE WHEN a.DATA_TYPE = 'varchar' THEN 'string'
                       WHEN a.DATA_TYPE = 'numeric' OR a.DATA_TYPE = 'smallint' THEN CASE WHEN a.Numeric_scale != 0 THEN 'double' ELSE 'int' END
                       WHEN a.DATA_TYPE = 'datetime' THEN 'string'
                       WHEN a.data_type = 'bit' THEN 'int'
                       ELSE a.DATA_TYPE
                  END + '   ' + a.COLUMN_NAME + CHAR(10) + '{' + CHAR(13)
                + ' get { return  _' + a.COLUMN_NAME + ';}' + CHAR(13)
                + ' set { _' + a.COLUMN_NAME + '=value;}' + CHAR(13) + '}'
        FROM    LandSaleAcc.INFORMATION_SCHEMA.COLUMNS a
        WHERE   TABLE_NAME = @TableName 
       
                   
     
    END

===================================================================
O/P:=

Sp_GetClsClassNew 'TABLENAME'

======================================================================
private string _CompCode;
public string   CompCode
{
 get { return  _CompCode;}
 set { _CompCode=value;}
}

Using Shared Variable in Crystal Report

//used Shared Variable In Crystal Report

//create Formula Emp_Code
whileprintingrecords;
shared numbervar code := field namd
//Put Code InGroup Selection On Sub Report
shared numbervar code;
field name = Code

Generate Random Number Between Two Values in SQL Server

//Generate Random Number Between Two Values in SQL Server

DECLARE @Random INT;

DECLARE @Upper INT;

DECLARE @Lower INT



-- This will create a random number between 1000 and 2000

SET @Lower = 1000 -- The lowest random number

SET @Upper = 2000 -- The highest random number

SELECT @Random =
ROUND(((@Upper - @Lower -1)
*
RAND()
+ @Lower), 0)

SELECT
Round(@Random,-2)



========================================================================

O/P:=1900

Use ProperCase Function in SQL Server

//String Proper display
create function properCase(@string varchar(8000)) returns varchar(8000) as

begin


    set @string = lower(@string)

    declare @i int

    set @i = ascii('a')

    while @i <= ascii('z')

    begin

        set @string = replace( @string, ' ' + char(@i), ' ' + char(@i-32))

        set @i = @i + 1

    end

    set @string = char(ascii(left(@string, 1))-32) + right(@string, len(@string)-1)
    return @string

end

=======================================================

select  dbo.properCase('this iS a teSt.')

=======================================================

O/P:=  This Is A Test.

How to determine total number of open/active connections in SQL Server?

//total number of open/active connections
SELECT
DB_NAME(dbid) as DBName,
COUNT(dbid) as NumberOfConnections,
loginame as LoginName
FROM
sys.sysprocesses
WHERE
dbid > 0
GROUP BY
dbid, loginame

Find a Parent Control Recursively In C#.Net

//Parent Control Recursively
private static Control FindControlParent(Control control, Type type)
        {
            Control ctrlParent = control;
            while((ctrlParent = ctrlParent.Parent) != null)
            {
                if(ctrlParent.GetType() == type)
                {
                    return ctrlParent;
                }
            }
            return null;
        }

Remove Non AlphaCharacters in Sql Server

//only Characters Display
Create Function [dbo].[RemoveNonAlphaCharacters](@Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin

    Declare @KeepValues as varchar(50)
    Set @KeepValues = '%[^a-z]%'
    While PatIndex(@KeepValues, @Temp) > 0
        Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')

    Return @Temp
End



===================================================================

select  dbo.RemoveNonAlphaCharacters('A1')

===================================================================

O/P:= A

Remove Alpha characters in SQL Server

//NonAlphaCharacters Display
Create Function [dbo].[RemoveNonAlphaCharacters](@Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin

    Declare @KeepValues as varchar(50)
    Set @KeepValues = '%[^a-z]%'
    While PatIndex(@KeepValues, @Temp) > 0
        Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')

    Return @Temp
End

Get Network Sql Server List

65t4rq//NetWork List
CREATE TABLE #servers(sname VARCHAR(500))
INSERT #servers (sname)
EXEC master..xp_CMDShell 'OSQL -L'
DELETE
FROM #servers
WHERE sname='Servers:'
OR sname IS NULL
SELECT LTRIM(sname)
FROM #servers
DROP TABLE #servers

Find First and Last Day of Current Month in SQL Server

//First and Last Day of Current Month in SQL Server

DECLARE @mydate DATETIME
SELECT @mydate = GETDATE()

SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@mydate)-1),@mydate),103) AS Date,
'First Day of Current Month' AS Type
UNION
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@mydate))),DATEADD(mm,1,@mydate)),103) AS Date ,
'Last Day of Current Month' AS Type



=======================================================================


==>O/P:=

   Date                       Type
01/06/2016  | First Day of Current Month
30/06/2016  | Last Day of Current Month

Use Stuff in SQL Server

//stuff keyword example

DECLARE @cols AS NVARCHAR(MAX);


SELECT @cols = STUFF((SELECT Distinct '],[' +
columnName
 FROM TableName
 FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '')+']';

SELECT @cols

O/P:=Fro Exmple ==>,[Apr-16],[Mar-16]

Thursday, June 2, 2016

registry delete in system

//registry delete in system
reg delete "HKEY_CURRENT_USER\Software\Microsoft\FTP\Accounts" /f

pdf file to image convert(user to ghostscript and gswin32.exe)

//pdf file to image convert(user to ghostscript and gswin32.exe)

            string ghostScriptPath = "\"" + System.Windows.Forms.Application.StartupPath + "\\gswin32.exe \"";
            string InputFileName = FileLocation.Replace("1.pdf", "watermark.pdf");
            string OutputFileName = @"Z:\1";

            PdfToImage(ghostScriptPath,InputFileName,OutputFileName );


 public void PdfToImage(string ghostScriptPath,string PdfFile,string ImageFile)
        {
                     
            String argu = "-dNOPAUSE -sDEVICE=jpeg -r400 -o" + ImageFile + "-%d.jpg " + PdfFile;
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo.FileName = ghostScriptPath;
            proc.StartInfo.Arguments = argu;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            proc.Start();
            proc.WaitForExit();

        }

hide files inside jpeg gif png images

copy /b 1.png + 123.rar 77.png

C#.net in Create notepad file and Write any Data

//File Write  
public static void File(string Message)
        {
            StreamWriter sw = null;
       

            try
            {
                string sLogFormat = DateTime.Now.ToShortDateString().ToString() + " | " + DateTime.Now.ToLongTimeString().ToString() + " | " + Global.UserName + " | " + Environment.MachineName + " ==> ";
                string sPathName = C:\ + "\\Log" + "\\";

                string sYear = DateTime.Now.Year.ToString();
                string sMonth = DateTime.Now.Month.ToString();
                string sDay = DateTime.Now.Day.ToString();

                string sErrorTime = sDay + "-" + sMonth + "-" + sYear;

                sw = new StreamWriter(sPathName + "Test_" + sErrorTime + ".txt", true);

                sw.WriteLine(sLogFormat + Message);
                sw.Flush();

            }
            catch (Exception ex)
            {
                ErrorLog(ex.ToString());
            }
            finally
            {
                if (sw != null)
                {
                    sw.Dispose();
                    sw.Close();
                }
            }


        }



===============================================================


O/P:= 05/05/2016 | 10:46:49 | ADMIN | TEST |  ==> HELLO.........