Saturday, August 13, 2016

Restore Database using C#.net


                        SqlConnection Con;
                        connect = new SqlConnection(String.Format("Data Source={0};Initial Catalog={1};User Id={2};Password={3};", ServerName, "master", UserName,Password));
                        Con.Open();
                       
                       SqlCommand command;
                        command = new SqlCommand("use master", Con);
                        command.ExecuteNonQuery();
                        SqlDataAdapter da = new SqlDataAdapter(@"use master Restore FILELISTONLY FROM DISK ='" + SelectPath + "'", Con);
                        DataSet mds = new DataSet();
                        da.Fill(mds);
                        if (mds == null)
                        {
                            MessageBox.Show("File not Support");
                            return;
                        }
                        command = new SqlCommand(@"RESTORE DATABASE " + mds.Tables[0].Rows[0][0].ToString() + " FROM DISK ='" + SelectPath + "' WITH MOVE '" + mds.Tables[0].Rows[0][0].ToString() + "' TO '" + RestoreFilePath + "\\" + mds.Tables[0].Rows[0][0].ToString() + ".mdf',REPLACE, MOVE '" + mds.Tables[0].Rows[1][0].ToString() + "' TO '" + RestoreFilePath + "\\" + mds.Tables[0].Rows[0][0].ToString() + "_log.ldf',REPLACE", Con);
                        command.CommandTimeout = 0;
                        command.ExecuteNonQuery();
                      

                        Con.Close();

Wednesday, August 3, 2016

Read MAC Address using asp.net

using  System.Management;


protected void Page_Load(object sender, EventArgs e)
    {
        string MacAdd = GetMACAddress();
        Response.Write("Mac Address is : " + MacAdd);
    }

   public string GetMACAddress()
    {
      ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguratin");
        ManagementObjectCollection moc = mc.GetInstances();
        string MacAdd = String.Empty;
        foreach (ManagementObject mo in moc)
        {
            if (MacAdd == String.Empty)
            {
                if ((bool)mo["IPEnabled"] == true) MacAdd = mo["MacAddress"].ToString();
            }
            mo.Dispose();
        }

        MacAdd = MACAddress.Replace(":", "");
        return MacAdd;
    }


Monday, August 1, 2016

Multiple File Upload in asp.net

Default.aspx

<div>
        <input type="file" id="FileUpload" multiple="multiple" runat="server" />
        <asp:Button runat="server" ID="btnupload" Text="Upload" OnClick="btnupload_Click" />&nbsp;<br/>
        <asp:Label runat="server" ID="lblName"></asp:Label>
    </div>


Default.aspx.cs

protected void btnupload_Click(object sender, EventArgs e)
        {        
            string savepath = Server.MapPath("foldername");
            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFile hpf = Request.Files[i];
                string filename = hpf.FileName;            
                hpf.SaveAs(savepath + @"\" + filename);
            }
        } 

run exe in asp.net

// Create a Process Object here.
System.Diagnostics.Process process1 = new System.Diagnostics.Process();
//Working Directory Of .exe File.
process1.StartInfo.WorkingDirectory = Request.MapPath("~/");
//exe File Name.
process1.StartInfo.FileName = Request.MapPath("Demo.exe");
//Arguments Which you have tp pass.
process1.StartInfo.Arguments = " ";
process1.StartInfo.LoadUserProfile = true;
 //Process Start on exe.
process1.Start();
process1.WaitForExit();

process1.Close();

Post Photo and Status On Facebook using asp.net

Default1.aspx.CS

protected void Page_Load(object sender, EventArgs e)
{
   FaceBookConnect.Authorize("publish_actions","http://localhost:123/Default2.aspx"); 

}


Default2.aspx

<html lang="en">  
<head id="Head1" runat="server"> </head>

<body>
    <form id="form1" runat="server">
        <asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine"></asp:TextBox>
        <asp:FileUpload ID="FileUpload1" runat="server"></asp:FileUpload>
        <hr />
        <asp:Button ID="btnUpload" runat="server" Text="Ulpoad" OnClick="btnUpload_Click" /> </form>
</body> 

</html>

Default2.aspx.CS


protected void Page_Load(object sender, EventArgs e)
{
    FaceBookConnect.API_Key = "App Key";
    FaceBookConnect.API_Secret = "App Secret Key";
    if (!IsPostBack)
    {
        string code = Request.QueryString["code"];
        if (!string.IsNullOrEmpty(code))
        {
            ViewState["Code"] = code;
        }
    }
}

protected void btnUpload_Click(object sender, EventArgs e)
{
    Dictionary < string, string > data = new Dictionary < string, string > ();
    data.Add("caption", "Chetan");
    data.Add("name", "Chetan");
    data.Add("message", txtMessage.Text);
    Session["File"] = FileUpload1.PostedFile;
    Session["Message"] = txtMessage.Text;
    FaceBookConnect.Post(ViewState["Code"].ToString(), "me/feed", data);
    FaceBookConnect.PostFile(ViewState["Code"].ToString(), "me/photos", (HttpPostedFile)   
Session["File"], Session["Message"].ToString());


}

Thursday, July 14, 2016

convert PDF to JPG image in C#.Net

//Pdf to jpg file Convert in C#.Net
 string cmd = "\"" + System.Windows.Forms.Application.StartupPath + "\\gswin64.exe \"";

       
            string argu = " -dNOPAUSE -dBATCH -dSAFER -sDEVICE=jpeg -djpegq=500 -r500  -dNumRenderingThreads=8 -sOutputFile=" + "\"" + System.Windows.Forms.Application.StartupPath + "\\" + FileName+ "%d.jpg" + "\" " + " \"" + PathAndFileName + "\"";
     
         
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo.FileName = cmd;
            proc.StartInfo.Arguments = argu;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            proc.Start();
            proc.WaitForExit();

Tuesday, July 12, 2016

JSON Support in SQL Server 2016

--JSON Support  in SQL Server 2016
Example:=

Select top(1) TrnNo,Amount
from Sale
For JSON  PATH, ROOT('TrnNo')

Output:=

{"TrnNo":[{"TrnNo":1,"Amount":100}]}

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