Tuesday, December 25, 2018

Security headers in .NET

You can inculde this on Global.ascx file at Application_BeginRequest function ib Vb.net and
Application_BeginRequest in c#

HttpContext.Current.Response.AddHeader("x-frame-options", "SAMEORIGIN") ' click-jacking attack's prevention
        HttpContext.Current.Response.Headers.Add("X-XSS-Protection", "1; mode=block") 'Cross-site scripting attack prevention
        HttpContext.Current.Response.Headers.Add("X-Content-Type-Options", "nosniff") ' MIME  attack prevention

Reference Link:
https://stackoverflow.com/questions/18337630/what-is-x-content-type-options-nosniff
https://www.keycdn.com/blog/x-xss-protection

This gives you a grade based on all of your security headers and you can see what you might be missing.
https://securityheaders.com

Wednesday, November 14, 2018

Convert Rows in to Columns in SQL

I am facing an issue in which I need to convert Rows in to Column in SQL.

SELECT id,
       video_data1,
       video_data2,
       video_data3
FROM   (  SELECT   (tv.id),
                    Cast(english_value AS  NVARCHAR(max)) AS 'English_value', tv.NAME AS 'Category_Name',
                    'Video_Data' + cast(row_number() OVER(partition BY tv.id ORDER BY tv.id) AS varchar(10))   columnsequence
                FROM     tv ) temp PIVOT ( max(english_value) FOR columnsequence IN (video_data1,
                                                                                     video_data2,
                                                                                     video_data3) ) piv

As you can see I am using Cast(english_value AS  NVARCHAR(max)), it due to I cannot use ntext in max so I need to change
data type .

After using Pivot: 


Refer Link:
https://www.youtube.com/watch?v=C0mQqDnF7wQ



Thursday, November 8, 2018

Multiple Language Caching in Asp.net

Recently I am facing an issue in which when ever user open a website some of the static control like slider hit our database. So what I have to do I need to prevent that hit and get data from Cache.
One more thing is that we support multiple language in our website its means when user login as English user he get data in English and when Chinese he will get Chinese and so on , So I need implement multiple language caching.

time define in web.config file
   Dim CacheTime As String = ConfigurationManager.AppSettings("CacheTime")

languageId in which i get language of user
 
If Cache("HomePage" & languageId.ToString()) IsNot Nothing Then
            ds = DirectCast(Cache("HomePage" & languageId.ToString()), DataSet)
        Else
            ds = GetHomePageContent(Me.languageId)
            Cache.Insert("HomePage" & languageId.ToString(), ds, Nothing, DateTime.Now.AddSeconds(Convert.ToInt32(CacheTime)), System.Web.Caching.Cache.NoSlidingExpiration)
        End If

Sunday, October 21, 2018

Access the directory by using local host


It is useful when we don't publish a website for local development, we can access the folder to show images etc
Paste this in <system.webServer> tag

  <directoryBrowse enabled="true" showFlags="Date,Time,Extension,Size" />
 
  </system.webServer>

Sunday, July 29, 2018

Iterate through a result set using Cursor or While Loop


There are different ways in which you can looping records of your table I just share some examples, Let you decide which fit best in you scenario.

DECLARE @Customer_id numeric
DECLARE @cur_emp as CURSOR;

SET @cur_emp = CURSOR FORWARD_ONLY FOR
Select  Coin_ID From test_auto

OPEN @cur_emp;
FETCH NEXT FROM @cur_emp INTO @Customer_id;
 WHILE @@FETCH_STATUS = 0
BEGIN
      print @Customer_id
     FETCH NEXT FROM @cur_emp INTO @Customer_id;
END
CLOSE @cur_emp;
DEALLOCATE @cur_emp;


GO

DECLARE @Customer_id numeric
DECLARE @cur_emp as CURSOR;

SET @cur_emp = CURSOR FAST_FORWARD  FOR
Select  Coin_ID From test_auto

OPEN @cur_emp;
FETCH NEXT FROM @cur_emp INTO @Customer_id;
 WHILE @@FETCH_STATUS = 0
BEGIN
      print @Customer_id
     FETCH NEXT FROM @cur_emp INTO @Customer_id;
END
CLOSE @cur_emp;
DEALLOCATE @cur_emp;


GO

DECLARE @Customer_id numeric
 DECLARE cur_emp CURSOR
STATIC FOR
Select  Coin_ID From test_auto
OPEN cur_emp
IF @@CURSOR_ROWS > 0
 BEGIN
 FETCH NEXT FROM cur_emp INTO @Customer_id
 WHILE @@Fetch_status = 0
 BEGIN
 print @Customer_id

 FETCH NEXT FROM cur_emp INTO @Customer_id
 END
END
CLOSE cur_emp
DEALLOCATE cur_emp
SET NOCOUNT OFF

GO


DECLARE @count INT
 DECLARE @row INT
 Declare @Coin_ID int
 SET @row = 1
 SELECT @count = COUNT(Coin_ID) FROM test_auto
 WHILE (@row <= @count)
 BEGIN
     Select  @Coin_ID = Coin_ID From test_auto

    --Do some processing here
print @Coin_ID
 SET @row += 1
END


Refer links:
https://docs.microsoft.com/en-us/sql/t-sql/language-elements/declare-cursor-transact-sql?view=sql-server-2017
https://sqlperformance.com/2012/09/t-sql-queries/cursor-options
https://www.techrepublic.com/blog/the-enterprise-cloud/comparing-cursor-vs-while-loop-performance-in-sql-server-2008/
http://stevestedman.com/2015/03/simple-cursor-example-forward_only-vs-fast-forward/


Saturday, July 28, 2018

Insert Bulk data in to table in .NET

In the last post I discuss how we insert bulk data by using SQL Server you can find here but there is an issue with that approach it only if your comma separated file exist on that SQL Server machine.
Let suppose I have a requirement in which user upload a comma separated text file from website and I need to insert that file in to SQL table  what I am facing right now my IIS Server and my Database server both are separate machine so in this case my previous post was not useful in this case .
I have a same file format which is

Coin_ID | Customer_ID | Coin_Address | BitCoins | Status_ID | Is_Active | Created_By | Updated_By | Updated_Date | Transaction_ID | Transfer_Type


7635 | 209285 | 1HqrLzm2jUqcNGi4YQtMstUcadNBzfuz39 | 0.019 | 4 | 1 | Finance | Finance | 06/08/2018 02:31:54 PM | 334fb8d949d4f2783060cac4ac238e13bb12gfgf3ce3c4943d9f8f5639e88 | 1

there are thirty thousand record if one record at a time using a SqlCommand along with a INSERT INTO statement is very costly and slow. You need an efficient solution to insert large number of records quickly thank God in .net SqlBulkCopy we can use this to fix this issue .

This is the main method that will insert in to table
   Using con As New SqlConnection("connectionstring")
            con.Open()
            Using sqlTransaction As SqlTransaction = con.BeginTransaction()
                Using sqlBulkCopy As New SqlBulkCopy(con, SqlBulkCopyOptions.Default, sqlTransaction)
                    sqlBulkCopy.DestinationTableName = "test_auto"
                    Try
                        sqlBulkCopy.WriteToServer(dt1) ' Pass datatable in to that
                        sqlTransaction.Commit()
                    Catch
                        sqlTransaction.Rollback()
                    End Try
                End Using
            End Using
            con.Close()
        End Using

Now I am sharing my whole code .

    Dim sValues As String()
        Dim lines As String()
 ' Read a textfile from that path
        lines = System.IO.File.ReadAllLines("C:\testinglargedate.txt")

' declare all my column that I previously share my table format
        Dim dt1 = New DataTable()
        dt1.Columns.Add("Coin_ID")
        dt1.Columns.Add("Customer_ID")
        dt1.Columns.Add("Coin_Address")
        dt1.Columns.Add("BitCoins")
        dt1.Columns.Add("Status_ID")
        dt1.Columns.Add("Is_Active")
        dt1.Columns.Add("Created_By")
        dt1.Columns.Add("Updated_By")
        dt1.Columns.Add("Updated_Date")
        dt1.Columns.Add("Transaction_ID")
        dt1.Columns.Add("Transfer_Type")

        Dim Coin_ID As Integer
        Dim Customer_ID As Integer
        Dim Coin_Address As String
        Dim BitCoins As Decimal
        Dim Status_ID As Integer
        Dim Is_Active As Integer
        Dim Created_By As String
        Dim Updated_By As String
        Dim Updated_Date As DateTime
        Dim Transaction_ID As String
        Dim Transfer_Type As String

'Looping of each row and skipping the header the fill the values accordingly i Just add one for sample
        For Each sLine As String In lines
                sLine = Trim(sLine.TrimEnd())
            sValues = sLine.Split(" | ")
            If sValues.Length >= 11 AndAlso (sValues(0) <> "Coin_ID " And sValues(0) <> "Coin_ID") Then  'Checking NULL and Skipping the Header Row



                If Not String.IsNullOrEmpty(Convert.ToString(sValues(0))) Then
                    Coin_ID = Convert.ToInt32(sValues(0))
                Else
                    Coin_ID = Convert.ToInt32(0)
                End If

             

                dt1.Rows.Add(Coin_ID, Customer_ID, Coin_Address, BitCoins, Status_ID, Is_Active, Created_By, Updated_By,Updated_Date , Transaction_ID, Transfer_Type)



            End If

        Next



   Using con As New SqlConnection("connectionstring")
            con.Open()
            Using sqlTransaction As SqlTransaction = con.BeginTransaction()
                Using sqlBulkCopy As New SqlBulkCopy(con, SqlBulkCopyOptions.Default, sqlTransaction)
                    sqlBulkCopy.DestinationTableName = "test_auto"
                    Try
                        sqlBulkCopy.WriteToServer(dt1) ' Pass datatable in to that
                        sqlTransaction.Commit()
                    Catch
                        sqlTransaction.Rollback()
                    End Try
                End Using
            End Using
            con.Close()
        End Using

Refer link :
Great Help



Monday, July 23, 2018

Bulk Insert in SQL (Import CSV File Into SQL Server Using Bulk Insert – Load Comma Delimited File Into SQL Server)

I was working on one task in which I need to insert thousands of record  in database . I have a txt file in which pipe separate values are there, My file format is like this

Coin_ID | Customer_ID | Coin_Address | BitCoins | Status_ID | Is_Active | Created_By | Updated_By | Updated_Date | Transaction_ID | Transfer_Type


7635 | 209285 | 1HqrLzm2jUqcNGi4YQtMstUcadNBzfuz39 | 0.019 | 4 | 1 | Finance | Finance | 06/08/2018 02:31:54 PM | 334fb8d949d4f2783060cac4ac238e13bb12gfgf3ce3c4943d9f8f5639e88 | 1


One thing bulk will not support decimal values so the table you make that column as float
and number of columns should be the same as in csv and in table otherwise you get an error check last link
So my table format is like this

CREATE TABLE [dbo].[test_auto](
[Coin_ID] [int] NULL,
[Customer_ID] [varchar](50) NULL,
[Coin_Address] [varchar](100) NULL,
[BitCoins] float NULL,
[Status_ID] [int] NULL,
[Is_Active] [int] NULL,
[Created_By] [varchar](50) NULL,
[Updated_By] [varchar](50) NULL,
[Updated_Date] [datetime] NULL,
[Transaction_ID] [varchar](100) NULL,
[Transfer_Type] [int] NULL
) ON [PRIMARY]
GO

There are two ways you can make SP and pass the value or if you are using only one time then use the normal script . i will share both of them

Simple Script :

BULK
INSERT test_auto
FROM 'C:OutputFile_08062018143155.txt'
WITH
(
FIELDTERMINATOR = '|',
ROWTERMINATOR = '\n',
FIRSTROW=2

)
let me explain line by line
I have create a table with the name of test_auto in which i have to insert my all values after that i define my path where is my file located.Third thing FIELDTERMINATOR  is a parameter in which you define what value separate the two words right now mine was pipe sign you can use what ever you want. ROWTERMINATOR  is end of the row .FIRSTROW is  which line you want to read my first row is my heading so I want to start from second row.

Store Procedure:

CREATE PROC BulkInserttest (@FilePath VARCHAR(100), @FileFieldterminator VARCHAR(5))
AS
BEGIN
SET NOCOUNT ON;
--Truncate the existing data from table
TRUNCATE TABLE dbo.test_auto
--Declare the local variable
DECLARE @bulkinsert NVARCHAR(2000)

SET @bulkinsert = 
   'BULK INSERT dbo.test_auto
   FROM ''' +  @FilePath + '''
   WITH
   (
    FIRSTROW = 2,
    FIELDTERMINATOR = '''+ @FileFieldterminator +''',
    ROWTERMINATOR = ''\n''
   )'
--Execute the BULK INSERT statement    
EXEC (@bulkinsert)
--Print the number of rows affected
PRINT CAST(@@ROWCOUNT AS VARCHAR(5))+ ' Rows Inserted'
RETURN (@@ROWCOUNT)
--The number of rows affected by a Transact-SQL statement will return thereafter
SET NOCOUNT OFF;
END
GO

Now if you want to run this :

exec BulkInserttest  'C:OutputFile_08062018143155.txt','|'

Refer links:
Other Parameters
Help
Bulk Insert with Decimal values

Tuesday, July 17, 2018

Fancy Box-Refresh parent page and close iframe popup from Server Side(C# and Vb.net)

I have a scenario in which i need to close Popup forcefully when the user hit save or reject button and refresh the parent page.
just add this line on button click

//parent.showloader() is my loder function in my main page to show loading image

ClientScript.RegisterStartupScript([GetType](), "Javascript", "parent.$.fancybox.close(); parent.showloader(); parent.location.reload(true);", True)


Friday, July 13, 2018

SQL Server Store Procedure Log

I was currently going through one process in which i need to fix some urgent issues. As a developer we normally use error log in our server side code but what if there some Database logging  as well.
let suppose your end user face any issue then you need to replicate the same scenario again by connecting you code with database and passing the same arguments it is time consuming obviously.
So i was thinking if i know the exact parameter list of user and at what line database error occur so I can fix easily and quickly .
So I create a table structure like this you can add more columns if you like but for me its quite enough to  rectify the issue.

Table Structure:

CREATE TABLE [StoreProcedureLog](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[EntryDatetime] [datetime] NULL,
[ErrorLine] [int] NULL,
[ErrorMessage] [nvarchar](1000) NULL,
[ProcedureName] [varchar](1000) NULL,
[AdditionalInfo] [varchar](1000) NULL,
[Status] [int] NULL,
 CONSTRAINT [PK_StoreProcedureLog] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [StoreProcedureLog] ADD  CONSTRAINT [DF_StoreProcedureLog_EntryDatetime]  DEFAULT (getdate()) FOR [EntryDatetime]
GO
ALTER TABLE [StoreProcedureLog] ADD  CONSTRAINT [DF_StoreProcedureLog_Status]  DEFAULT ((1)) FOR [Status]
GO

let me explain column one by one
ID = Auto Increment Column
EntryDatetime = It give you idea at what time error occur and no need to write insert for this as i set default value is Getdate()
ErrorLine = It will tell you the exact line number of error
ErrorMessage = It will tell you the error message
ProcedureName = It will tell you the name of procedure
AdditionalInfo = Pass extra information for this I normally pass my parameters list so I can know what was the exact scenario
Status= I set default value is 1 ( I use this when I fix the issue I marked that status =0 Its mean i solve that issue)

Store Procedure :

CREATE PROCEDURE Insertsplog @ERROR_PROCEDURE NVARCHAR(max) = NULL,
                            @AdditionalInfo  NVARCHAR(max) = NULL
AS
  BEGIN
      --SET NOCOUNT ON;
      IF EXISTS (SELECT 1
                 FROM   information_schema.tables
                 WHERE  table_name = 'StoreProcedureLog')
        BEGIN
            INSERT INTO storeprocedurelog
                        (errorline,
                         errormessage,
                         procedurename,
                         additionalinfo)
            VALUES      (Error_line(),
                         Error_message(),
                         @ERROR_PROCEDURE,
                         @AdditionalInfo);
        END

  END

Calling SP:

CREATE PROC Sp
AS
  BEGIN
      BEGIN try
       -- Your Sp logic here
      END try
      BEGIN catch
          IF EXISTS (SELECT 1
                     FROM   information_schema.routines
                     WHERE  routine_name = 'InsertSpLog')
            BEGIN
                DECLARE @ERROR_PROCEDURE NVARCHAR(1000);
DECLARE @Comments NVARCHAR(1000)
                 SET  @Comments='Id: ' +CONVERT(varchar(10), @Id) -- Passing Information so easy to find the root cause for crashing the store procedure

                SET @ERROR_PROCEDURE=Error_procedure(); -- it will pass the Store Proc name

                --EXEC Insertsplog  @ERROR_PROCEDURE -- Passing without Comments
         EXEC Insertsplog  @ERROR_PROCEDURE,@Comments -- Passing with Comments
            END
      END catch

  END

This was the following result









Thursday, July 5, 2018

ASP.NET Session Timeout

In web.config file add this line of code
<configuration>
  <system.web>
   <sessionState timeout="90" />  <!--90 minutites-->
  </system.web>
</configuration>

Reference link 

Tuesday, July 3, 2018

Generate Random String in C# and Vb.net

In this method just pass the length , it will generate a random string.

VB.net :

    Public Function GetRandomString(ByVal length As Integer) As String
        'use the following string to control your set of alphanumeric characters to choose from
        'you could also include lowercase or punctuation too
        Const alphabet As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"


        Dim result As New StringBuilder(length)


        ' Random is not truly random,
        ' so we try to encourage better randomness by using a seed value
        Static rnd As New Random(Convert.ToInt32(DateTime.Now.Ticks And Integer.MaxValue))

        Dim prevChar As String = String.Empty
        Dim nextChar As String
        Do While result.Length < length
            nextChar = alphabet.Substring(rnd.[Next](0, alphabet.Length), 1)
            If nextChar.Equals(prevChar) = False Then
                result.Append(nextChar)
                prevChar = nextChar
            End If
        Loop
        Return result.ToString
    End Function


C#

   private static Random random = new Random();
        public static string GetRandomString(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[random.Next(s.Length)]).ToArray());
        }

Wednesday, June 20, 2018

Working with bitcoin Core Wallet Part 2

In this previous post I share how we install bitcoin core you can find that pose here
Now these are some links that help me when I was start working on my project,you can follow the link as step by step.There are some issues that i was facing while i was working on that
project mainly was implementation of LockUnspent 


Concept of BTC :
https://www.youtube.com/channel/UCXIv02S77csw3Sqoaj76UeQ/videos

Test BTC Coins:
https://tpfaucet.appspot.com/
https://testnet.blockchain.info/ (Check transaction)

API Help:
http://chainquery.com/bitcoin-api
https://www.multichain.com/developers/api-errors/
https://en.bitcoin.it/wiki/Running_Bitcoin
https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_calls_list
https://www.multichain.com/developers/api-errors/

This link is help in such a way you can actually see reason why it sending error in response (i.e Real code of BTC RPC Call)
https://goo.gl/1sYHsZ




Code for BTC  wrapper :
You can find lots of Bitcoin c# wrapper but I used first link mainly and adding more methods that is not here such as LockUnspent,ListLockUnspent

https://github.com/iancoleman/bitcoin-qr-popup/blob/master/src/bitnet/Bitnet.Client/BitnetClient.cs
https://bitcointalk.org/index.php?topic=294807.0
https://github.com/iancoleman/bitcoin-qr-popup
https://github.com/MetacoSA/NBitcoin/blob/master/NBitcoin/RPC/RPCClient.Wallet.cs
https://github.com/GeorgeKimionis/BitcoinLib
https://www.youtube.com/watch?v=ya5ByOqFF2U&list=PLskt7tlkTFy8fElITkV69-n1zdGPPn_SU
https://bitcoin.stackexchange.com/questions/32462/blockchain-programming-books-c

UTXO:
This is the main topic how actually Transaction work
https://www.youtube.com/watch?v=YjiE4SZtSlY&t=533s

This is the main topic that i faced lot of issues, see this post you get an idea ;)
https://github.com/bitcoin/bitcoin/issues/10004



Mempool:
https://www.youtube.com/watch?v=PeINuxxZAyg
https://jochen-hoenicke.de/queue/#1,30d
https://blockchain.info/charts/mempool-size
https://bitcoin.stackexchange.com/tags/mempool/hot
https://gist.github.com/laanwj/efe29c7661ce9b6620a7
https://medium.com/@octskyward/mempool-size-limiting-a3f604b72a4a
https://www.reddit.com/r/Bitcoin/comments/7kopyg/serious_if_the_mempool_size_keeps_increasing_what/

SegWit :
https://medium.com/verifyas/segwit-the-solution-to-the-problem-7c5c58711b43
https://bitcoinmagazine.com/articles/bitcoin-core-0160-released-heres-whats-new/

Tuesday, May 15, 2018

Bind DropDownList using JavaScript and ASP.Net AJAX and Web Method

Add this code on your asp.x page 

<head runat="server">

    <title></title>

    <script src="Scripts/jquery-3.1.1.js"></script>



</head>

<body>

    <form id="form1" runat="server">

        <div>

            <asp:DropDownList ID="RejectionReasons" runat="server"></asp:DropDownList>

            <label id="lblRequired" style="color: red; float: left; text-align: left !important"></label>

            <asp:Button ID="btnAction" runat="server" CssClass="button" OnClick="ActionPopUp_Click" CausesValidation="True" Text="" ValidationGroup="SaveRR" OnClientClick="return isRejectReasonSelected();" />

            <asp:HiddenField runat="server" ID="hdn_SelectedReasonText" />

            <asp:HiddenField runat="server" ID="hdn_SelectedReasonID" />

        </div>

    </form>
    <script>

   function isRejectReasonSelected()
        {
            $('#lblRequired').text('');
            var isAnyItemSelected = false;
            $('#<%=RejectionReasons.ClientID%> :selected').each(function(i, selected){
                isAnyItemSelected = true;
             
            });
            if(isAnyItemSelected){
                var values = "";
                var text = "";
                var selected = $("[id*=RejectionReasons] option:selected");
                selected.each(function () {
                    values += $(this).val() + "," ;
                    text += $(this).html() + ";" ;
                });
                $('#<%=hdn_SelectedReasonText.ClientID%>').val(text);
                $('#<%=hdn_SelectedReasonID.ClientID%>').val(values);
                return isAnyItemSelected;
            }
            else
            {
                $('#lblRequired').text('Please select reason');
                return isAnyItemSelected;
            }


         
        }

        $(document).ready(function () {
                        var l_id =$("input[id*='hdn_parm']").val();  // I need to pass this on server side
                        var url = 'Details.aspx/DropDownBinding'
                        $.ajax({
                            url: url,
                            type: 'POST',
                            data: JSON.stringify({
                                l_id: l_id
                            }),
                            contentType: 'application/json; charset=utf-8',
                            dataType: "json",
                            success: function (response) {
                                $.each(response.d, function (i, val) { //bind data
                                    $("[id*=RejectionReasons]").append('<option value="' + val[1] + '">' + val[0] + '</option>');
                     

                            },
                            error: function (request, status, error) {

                            }
                        });
    });
    </script>
</body>

Add this code on server side:

using System.Web.Services;
[WebMethod(EnableSession = true)]
public static List<string[]> DropDownBinding(string l_id)
{
    Customer obj = new Customer();
    DataSet ds;
    ds = obj.getdata(l_id); // get data from database
    DataTable dt = ds.Tables(0);
    List<string[]> list = new List<string[]>();
    foreach (DataRow r in dt.Rows)
    {
        string[] a = new string;
        a[0] = r(0).ToString();
        a[1] = r(1).ToString();
        list.Add(a);
    }

    return list;
}



Thursday, April 26, 2018

Working with bitcoin Core Wallet Part 1

Its almost been a one month I am working  on Bitcoin project so I am thinking I share my knowledge how you start . Right now I am working in C# I have  a requirement in which i have to send bulk of bitcoin there are some scenario that I am facing I will share this on day by day whenever i get time .
so start this.

First download a bitcoin Core wallet right now 0.16.0 is released after ,You can find multiple link how to install  YouTube link for Installation.

After installation we need a test wallet so you just right click of exe go the properties and add space and  -testnet




After doing this when you open your screen look like this .PS right now i am using 0.15.0 version



Now we want Test net BTC coins for testing, there are lots of website you can find on this link
Test net BTC.

I will continue the coding part in next part ..




Tuesday, April 17, 2018

Get proper error message when webRequest.GetResponse failed (status code 500)

Right now i am working on bitcoin core wallet application when ever i send request on http request if it is failed it always return
500 status code not a meaning full error message so after googling i found this so i can easily trace
out at what reason it send failed.


after try block  add this

 catch (WebException ex)
            {
                using (var stream = ex.Response.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    var error = reader.ReadToEnd();
                    CustomLogger.Log("Custom Error Desc: " + Convert.ToString(error));

                }
           
            }

ref:

Link for help

Saturday, April 14, 2018

make comma separated and Remove empty lines and spaces in notepad++

Make comma separated:
Find-what box: (\d+)
Replace-with box: \1,
Search mode: ☑ Regular expression

Remove empty lines and spaces:
Use ^\s* for "Find what" and leave "Replace with" blank.

Tuesday, March 13, 2018

Query to find missing Indexes in DB

SELECT TOP 1000000
dm_mid.database_id AS DatabaseID,
dm_migs.avg_user_impact*(dm_migs.user_seeks+dm_migs.user_scans) Avg_Estimated_Impact,
dm_migs.last_user_seek AS Last_User_Seek,
OBJECT_NAME(dm_mid.OBJECT_ID,dm_mid.database_id) AS [TableName],
'CREATE INDEX [IX_' + OBJECT_NAME(dm_mid.OBJECT_ID,dm_mid.database_id) + '_'
+ REPLACE(REPLACE(REPLACE(ISNULL(dm_mid.equality_columns,''),', ','_'),'[',''),']','') 
+ CASE
WHEN dm_mid.equality_columns IS NOT NULL
AND dm_mid.inequality_columns IS NOT NULL THEN '_'
ELSE ''
END
+ REPLACE(REPLACE(REPLACE(ISNULL(dm_mid.inequality_columns,''),', ','_'),'[',''),']','')
+ ']'
+ ' ON ' + dm_mid.statement
+ ' (' + ISNULL (dm_mid.equality_columns,'')
+ CASE WHEN dm_mid.equality_columns IS NOT NULL AND dm_mid.inequality_columns 
IS NOT NULL THEN ',' ELSE
'' END
+ ISNULL (dm_mid.inequality_columns, '')
+ ')'
+ ISNULL (' INCLUDE (' + dm_mid.included_columns + ')', '') AS Create_Statement
FROM sys.dm_db_missing_index_groups dm_mig
INNER JOIN sys.dm_db_missing_index_group_stats dm_migs
ON dm_migs.group_handle = dm_mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details dm_mid
ON dm_mig.index_handle = dm_mid.index_handle
WHERE dm_mid.database_ID = DB_ID()
ORDER BY Avg_Estimated_Impact DESC

SQL Server table creation date query

This query will tell you when this table is created.


SELECT [name]        AS [TableName], [create_date] AS [CreatedDate] 
FROM   sys.tables 
WHERE  NAME = 'user' -- table name

Saturday, March 3, 2018

Run query on dataset

if you want to query on dataset you can simply do this no need to again hit database:

-- storing in Dataset
  Dim ds As New DataSet
    Dim ds_1 As New DataSet
   ds = getData()
   Session("ds_data") = ds


 -- Retrieving from Dataset
      Dim foundRows() As DataRow
       ds_1 = DirectCast(Session("ds_data"), DataSet) ' get data from session data
foundRows = ds.Tables(0).Select("table_ID = '" + hdn_ID.Value + "' ") ' table_ID is my column name
dim user_name as String =foundRows(0)("Customer Name")

-- Another Option
One more you can do you can make a new data-set and copy that filter data in to new data-set

Dim ds_Stats As DataSet
Dim ds_StatsAddress As DataSet
Dim ds_StatsPic As DataSet
ds_Stats = oApproveaddress.getData()
            ds_StatsPic = New DataSet()
            ds_StatsPic.Merge(ds_Stats.Tables(0).Select("id = '3' "))
            ds_StatsAddress = New DataSet()
            ds_StatsAddress.Merge(ds_Stats.Tables(0).Select("id = '4' "))


If ds_Stats.Tables(0).Select("documentid = '3' ").Length > 0 Then
                RepeaterPic.DataSource = ds_StatsPic.Tables(0)
                RepeaterPic.DataBind()
            Else
                RepeaterPic.DataSource = Nothing
                RepeaterPic.DataBind()
            End If


            If ds_Stats.Tables(0).Select("documentid = '4' ").Length > 0 Then
                RepeaterAddress.DataSource = ds_StatsAddress.Tables(0)
                RepeaterAddress.DataBind()
            Else
                RepeaterAddress.DataSource = Nothing
                RepeaterAddress.DataBind()
            End If

-- Sorting in Dataset

  Dim ds_Re As DataSet
        ds_Re= New DataSet()
        ds_Re.Merge(ds.Tables(0).Select("", "Date DESC"))
        If ds.Tables(0).Select("Is_Recommended = True ").Length > 0 Then
            rptReco.DataSource = ds_Recommended.Tables(0)
            rptReco.DataBind()

        End If

Refer

Thursday, March 1, 2018

Find Stored Procedure that Inserts Into a Specific Table

SELECT O.NAME
FROM   sysobjects O
       JOIN syscomments C
         ON O.id = C.id
WHERE  C.text LIKE '%insert into%user_log%' 

Wednesday, January 3, 2018

Split function in SQL

I have a scenario in which I have a comma seperted value list which I need to use get data from another table.

so if I can use IN query with this my split function it can work like a charm.


CREATE FUNCTION Split 

 @RowData nvarchar(MAX), 
 @SplitOn nvarchar(50) 
)   
RETURNS @RtnValue table   

 Id int identity(1,1), 
 Data nvarchar(100) 
)   
AS   
BEGIN   
 Declare @Cnt int 
 Set @Cnt = 1 
 
 While (Charindex(@SplitOn,@RowData)>0) 
 Begin 
  Insert Into @RtnValue (data) 
  Select   
   Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1))) 
 
  Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData)) 
  Set @Cnt = @Cnt + 1 
 End 
   
 Insert Into @RtnValue (data) 
 Select Data = ltrim(rtrim(@RowData)) 
 
 Return 
END

After make this function then we can call like this

DECLARE @listStr Nvarchar(max)
SELECT @listStr = COALESCE(@listStr+',','') +name  FROM A
SELECT @listStr  -- In this i get my values in comma seperted listStr

select Contact_Person,Role_Name from B where B.Name in (select data from dbo.split(@listStr,','))
-- in data it will split out my comma seperted list 

Ref:
http://www.aspforums.net/Threads/646179/Convert-comma-separated-int-values-to-string-values/