Wednesday, August 7, 2019

How to Integrate Google reCaptcha with asp.net

Step 1. Include following js at top of the .aspx page.
src="https://www.google.com/recaptcha/api.js?onload=renderRecaptcha&render=explicit" async defer

Step 2. Put following code into .aspx page.
Kindly put starting tag(<>) and ending tag(</>)
div class="form-group"
                                    div id="ReCaptchContainer" /div
                                   label id="lblMessage" runat="server" clientidmode="static" label
/div

Step 3. Put following javascript at the bottom of the .aspx page.


         var your_site_key = 'SITE_KEY';
        var renderRecaptcha = function () {
            grecaptcha.render('ReCaptchContainer', {
                'sitekey': your_site_key,
                'callback': reCaptchaCallback,
                theme: 'light', //light or dark   
                type: 'image',// image or audio   
                size: 'normal'//normal or compact   
            });
        };

        var reCaptchaCallback = function (response) {
            if (response !== '') {
                jQuery('#lblMessage').css('color', 'green').html('Success');
            }
        };

        jQuery('button[type="button"]').click(function (e) {
            var message = 'Please check the checkbox';
            if (typeof (grecaptcha) != 'undefined') {
                var response = grecaptcha.getResponse();
                (response.length === 0) ? (message = 'Captcha verification failed') : (message = 'Success!');
            }
            jQuery('#lblMessage').html(message);
            jQuery('#lblMessage').css('color', (message.toLowerCase() == 'success!') ? "green" : "red");
        });
   

Step 4. Put following function into .aspx.cs file

public bool IsReCaptchValid()
    {
        var result = false;
        var captchaResponse = Request.Form["g-recaptcha-response"];
        var secretKey = "SECRET_KEY";
        var apiUrl = "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}";
        var requestUri = string.Format(apiUrl, secretKey, captchaResponse);
        var request = (HttpWebRequest)WebRequest.Create(requestUri);

        using (WebResponse response = request.GetResponse())
        {
            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {
                JObject jResponse = JObject.Parse(stream.ReadToEnd());
                var isSuccess = jResponse.Value("success");
                result = (isSuccess) ? true : false;
            }
        }
        return result;
    }

Step 5. Validate IsReCaptchValid() function on Submit button click event

if (IsReCaptchValid())
        {
//Code for insert and send email to user/client
}
else
        {
            lblMessage.InnerHtml = (IsReCaptchValid())
         ? "span style='color:green'>Captcha verification success /span>"
         : "span style='color:red'>Captcha verification failed /span>";
        }

Thursday, July 11, 2019

How to Create and Download pdf using iTextSharp

 StringReader sr = new StringReader(strMailBody.ToString());//strMailBody is a html string generated using html template.
        Document pdfDoc = new Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        using (MemoryStream memoryStream = new MemoryStream())
        {
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
            pdfDoc.Open();

            htmlparser.Parse(sr);
            pdfDoc.Close();

            byte[] bytes = memoryStream.ToArray();
            memoryStream.Close();


            // Clears all content output from the buffer stream               
            Response.Clear();
            // Gets or sets the HTTP MIME type of the output stream.
            Response.ContentType = "application/pdf";
            // Adds an HTTP header to the output stream
            Response.AddHeader("Content-Disposition", "attachment; filename=SponsorshipForm.pdf");

            //Gets or sets a value indicating whether to buffer output and send it after
            // the complete response is finished processing.
            Response.Buffer = true;
            // Sets the Cache-Control header to one of the values of System.Web.HttpCacheability.
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            // Writes a string of binary characters to the HTTP output stream. it write the generated bytes .
            Response.BinaryWrite(bytes);
            // Sends all currently buffered output to the client, stops execution of the
            // page, and raises the System.Web.HttpApplication.EndRequest event.

            Response.End();
            // Closes the socket connection to a client. it is a necessary step as you must close the response after doing work.its best approach.
            Response.Close();
        }

Friday, September 28, 2018

How to Redirect Whole Classic ASP site from http to https (Force SSL for Specific Pages)

You have to open .asp file which is included each and every page of whole website like header.asp, leftmenu.asp, bottom.asp.

Write given below code at the top of this .asp file.

<%
   If Request.ServerVariables("SERVER_PORT")=80 Then
      Dim strSecureURL
      strSecureURL = "https://"
      strSecureURL = strSecureURL & Request.ServerVariables("SERVER_NAME")
      strSecureURL = strSecureURL & Request.ServerVariables("URL")
      Response.Redirect strSecureURL
   End If
%>

Monday, January 9, 2017

How to move label, textbox or any control like (marquee in html) in windows application

1. Take timer control into windows form.
2. Then create timer1_Tick event into .cs file.
3. Write following code within timer1_Tick event.

label.Location = new Point(label.Location.X + 5, label.Location.Y);

            if (label.Location.X > this.Width)
            {
                label.Location = new Point(0 - label.Width, label.Location.Y);
            }

Tuesday, September 8, 2015

Function for check table is exist or not in sql database

public int CheckTable(string TableName)
        {
            int i = 0;
            string cmdText = @"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES
                       WHERE TABLE_NAME='" + TableName + "') SELECT 1 ELSE SELECT 0";
            i = (int)ExecuteScalar(cmdText,CommandType.Text,null,null);
            return i;
        }

Tuesday, May 12, 2015

How to Find Column From All Tables of Database

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
ORDER BY schema_name, table_name;

How to find a string from whole database?

DECLARE @MyValue NVarChar(4000) = 'something';

SELECT S.name SchemaName, T.name TableName
INTO #T
FROM sys.schemas S INNER JOIN
     sys.tables T ON S.schema_id = T.schema_id;

WHILE (EXISTS (SELECT * FROM #T)) BEGIN
  DECLARE @SQL NVarChar(4000) = 'SELECT * FROM $$TableName WHERE (0 = 1) ';
  DECLARE @TableName NVarChar(1000) = (
    SELECT TOP 1 SchemaName + '.' + TableName FROM #T
  );
  SELECT @SQL = REPLACE(@SQL, '$$TableName', @TableName);

  DECLARE @Cols NVarChar(4000) = '';

  SELECT
    @Cols = COALESCE(@Cols + 'OR CONVERT(NVarChar(4000), ', '') + C.name + ') = CONVERT(NVarChar(4000), ''$$MyValue'') '
  FROM sys.columns C
  WHERE C.object_id = OBJECT_ID(@TableName);

  SELECT @Cols = REPLACE(@Cols, '$$MyValue', @MyValue);
  SELECT @SQL = @SQL + @Cols;

  EXECUTE(@SQL);

  DELETE FROM #T
  WHERE SchemaName + '.' + TableName = @TableName;
END;

DROP TABLE #T;

Friday, May 1, 2015

How to get the row count for all tables in a SQL SERVER database

CREATE TABLE #counts
(
    table_name varchar(255),
    row_count int
)

EXEC sp_MSForEachTable @command1='INSERT #counts (table_name, row_count) SELECT ''?'', COUNT(*) FROM ?'
SELECT table_name, row_count FROM #counts ORDER BY table_name, row_count DESC

How to drop all the tables from any database ?

DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR

SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME

OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql

WHILE (@@FETCH_STATUS = 0)
BEGIN
Exec SP_EXECUTESQL @Sql
FETCH NEXT FROM @Cursor INTO @Sql
END

CLOSE @Cursor DEALLOCATE @Cursor
GO

EXEC sp_MSForEachTable 'DROP TABLE ?'
GO

Tuesday, March 24, 2015

LINQ : Single, SingleOrDefault, First and FirstOrDefault

Single

Returns a single specific element from a collection of elements when element match found. An exception is thrown, when none or more than one match found for that element in the collection.

SingleOrDefault

Returns a single specific element from a collection of elements when element match found. An exception is thrown, when more than one match found for that element in the collection. A default value is returned, when no match is found for that element in the collection.

First

Returns first specific element from a collection of elements when one or more than one match found for that element. An exception is thrown, when no match is found for that element in the collection.

FirstOrDefault

Returns first specific element from a collection of elements when one or more than one match found for that element. A default value is returned, when no match is found for that element in the collection.

When to use Single, SingleOrDefault, First and FirstOrDefault


  1. If you want an exception to be thrown if the result set contains many records, use Single or SingleOrDefault.
  2. If you want a default value is returned if the result set contains no record, use SingleOrDefault.
  3. If you always want one record no matter what the result set contains, use First or FirstOrDefault.
  4. If you want a default value if the result set contains no record, use FirstOrDefault.

Perfomance of SingleOrDefault and FirstOrDefault

FirstOrDefault usually perform faster as compared SingleOrDefault, since it's iterate the collection until they find the first match. While SingleOrDefault iterate the whole collection to find one single match.

Tuesday, February 17, 2015

How to declare variable in php.

1. Start with a "$"
2. Followed by letter or underscore
3. Can contain letters, numbers, underscores or dashes
4. No spaces
5. Case sensitive

Example : Variable names

$item
$Item
$myVariable
$this_variable
$this-variable
$product1
$_book
$__bookPage

But, I recommend that do not use these from the above variable declaration
$this-variable,
$_book - Because php uses _ sign internally for many things
$__bookPage 

Monday, June 2, 2014

How to convert List to Datatable in vb.net

Public Function ConvertToDataTable(Of T)(ByVal list As IList(Of T)) As DataTable
        Dim table As New DataTable()
        Dim fields() As FieldInfo = GetType(T).GetFields()
        For Each field As FieldInfo In fields
            table.Columns.Add(field.Name, field.FieldType)
        Next
        For Each item As T In list
            Dim row As DataRow = table.NewRow()
            For Each field As FieldInfo In fields
                row(field.Name) = field.GetValue(item)
            Next
            table.Rows.Add(row)
        Next
        Return table
    End Function

Thursday, April 17, 2014

How to parse json string to dataset in C#

// Serialization of DataSet to json string
StringWriter sw = new StringWriter();
versionUpGetData.WriteXml(sw, XmlWriteMode.WriteSchema);
XmlDocument xd = new XmlDocument();
xd.LoadXml(sw.ToString());
String jsonText = JsonConvert.SerializeXmlNode(xd);
File.WriteAllText(“d:/datasetJson.txt”,jsonText);

//Deserialization of Json String to DataSet
XmlDocument xd1 = new XmlDocument();
xd1 = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonText);
DataSet jsonDataSet = new DataSet();
jsonDataSet.ReadXml(new XmlNodeReader(xd1));

Monday, February 10, 2014

What is final class in Object Oriented Programming

Final Class: A class that is defined as final class can not be inherited further. All Methods of a final class are inherently final and must not be declared as final in the class definition. Also, a final method can not be redefined further.
If only a method of a class is final then that class can be inherited but that method cannot be redefined.

Sunday, November 24, 2013

Install Skype on Ubuntu 12.04 LTS 64-bit

For 32Bit
Terminal Commands:
wget  http://download.skype.com/linux/skype-ubuntu-lucid_4.2.0.11-1_i386.deb
sudo dpkg -i skype-ubuntu-lucid_4.2.0.11-1_i386.deb
sudo apt-get -f install;rm skype-ubuntu-lucid_4.2.0.11-1_i386.deb
 
For 64Bit Terminal Commands:
sudo dpkg --add-architecture i386
sudo apt-get install ia32-libs
sudo apt-get update
wget http://download.skype.com/linux/skype-ubuntu-lucid_4.2.0.11-1_i386.deb
sudo dpkg -i skype-ubuntu-lucid_4.2.0.11-1_i386.deb
sudo apt-get -f install;rm skype-ubuntu-lucid_4.2.0.11-1_i386.deb
After all of this run in terminal sudo apt-get install sni-qt:i386; This will restore the skype contact window
That's all, work done in maximum 5 minutes. I use Ubuntu on 64bit and this method to install Skype worked always perfectly.

Friday, September 13, 2013

How to remove unused usings from class file ?

When we create a .cs file means code file class is automatically create. That .cs file means class has default usings for namespace.


using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;

We don't use all namespaces  in that class so we have to remove unused namespaces from file. We can remove  namespace manually but it takes time and need full knowledge of class library so we can use Visual Studio .

Step 1:  Right Click in .cs File.
Step 2:  Move on Organize usings.
Step 3: Click on Remove Unused Usings.

After that we have only those namespaces in the file these are using.
 

Wednesday, September 11, 2013

Programatically create a table using c#

Table tbl = new Table();
        tbl.ID = "table1";

        this.Controls.Add(tbl);

        for (int row = 0; row < 5; row++)
        {
            TableRow rw = new TableRow();


            TableCell cell = new TableCell();

            Label text = new Label();
            text.Text = "text";

            cell.Controls.Add(text);
            rw.Cells.Add(cell);

            tbl.Controls.Add(rw);

        }

Monday, September 9, 2013

IIS 7.0 informational HTTP status codes

1xx - Informational
These HTTP status codes indicate a provisional response. The client computer receives one or more 1xx responses before the client computer receives a regular response.

IIS 7.0 uses the following informational HTTP status codes:
100 - Continue.
101 - Switching protocols.

2xx - Success
These HTTP status codes indicate that the server successfully accepted the request.

IIS 7.0 uses the following success HTTP status codes:
200 - OK. The client request has succeeded.
201 - Created.
202 - Accepted.
203 - Nonauthoritative information.
204 - No content.
205 - Reset content.
206 - Partial content.

3xx - Redirection
These HTTP status codes indicate that the client browser must take more action to fulfill the request. For example, the client browser may have to request a different page on the server. Or, the client browser may have to repeat the request by using a proxy server.

IIS 7.0 uses the following redirection HTTP status codes:
301 - Moved permanently.
302 - Object moved.
304 - Not modified.
307 - Temporary redirect.

4xx - Client error
These HTTP status codes indicate that an error occurred and that the client browser appears to be at fault. For example, the client browser may have requested a page that does not exist. Or, the client browser may not have provided valid authentication information.

IIS 7.0 uses the following client error HTTP status codes:
400 - Bad request. The request could not be understood by the server due to malformed syntax. The client should not repeat the request without modifications.

IIS 7.0 defines the following HTTP status codes that indicate a more specific cause of a 400 error:
400.1 - Invalid Destination Header.
400.2 - Invalid Depth Header.
400.3 - Invalid If Header.
400.4 - Invalid Overwrite Header.
400.5 - Invalid Translate Header.
400.6 - Invalid Request Body.
400.7 - Invalid Content Length.
400.8 - Invalid Timeout.
400.9 - Invalid Lock Token.
401 - Access denied.

IIS 7.0 defines several HTTP status codes that indicate a more specific cause of a 401 error. The following specific HTTP status codes are displayed in the client browser but are not displayed in the IIS log:
401.1 - Logon failed.
401.2 - Logon failed due to server configuration.
401.3 - Unauthorized due to ACL on resource.
401.4 - Authorization failed by filter.
401.5 - Authorization failed by ISAPI/CGI application.
403 - Forbidden.

IIS 7.0 defines the following HTTP status codes that indicate a more specific cause of a 403 error:
403.1 - Execute access forbidden.
403.2 - Read access forbidden.
403.3 - Write access forbidden.
403.4 - SSL required.
403.5 - SSL 128 required.
403.6 - IP address rejected.
403.7 - Client certificate required.
403.8 - Site access denied.
403.9 - Forbidden: Too many clients are trying to connect to the Web server.
403.10 - Forbidden: Web server is configured to deny Execute access.
403.11 - Forbidden: Password has been changed.
403.12 - Mapper denied access.
403.13 - Client certificate revoked.
403.14 - Directory listing denied.
403.15 - Forbidden: Client access licenses have exceeded limits on the Web server.
403.16 - Client certificate is untrusted or invalid.
403.17 - Client certificate has expired or is not yet valid.
403.18 - Cannot execute requested URL in the current application pool.
403.19 - Cannot execute CGI applications for the client in this application pool.
403.20 - Forbidden: Passport logon failed.
403.21 - Forbidden: Source access denied.
403.22 - Forbidden: Infinite depth is denied.
404 - Not found.

IIS 7.0 defines the following HTTP status codes that indicate a more specific cause of a 404 error:
404.0 - Not found.
404.1 - Site Not Found.
404.2 - ISAPI or CGI restriction.
404.3 - MIME type restriction.
404.4 - No handler configured.
404.5 - Denied by request filtering configuration.
404.6 - Verb denied.
404.7 - File extension denied.
404.8 - Hidden namespace.
404.9 - File attribute hidden.
404.10 - Request header too long.
404.11 - Request contains double escape sequence.
404.12 - Request contains high-bit characters.
404.13 - Content length too large.
404.14 - Request URL too long.
404.15 - Query string too long.
404.16 - DAV request sent to the static file handler.
404.17 - Dynamic content mapped to the static file handler via a wildcard MIME mapping.
404.18 - Querystring sequence denied.
404.19 - Denied by filtering rule.
405 - Method Not Allowed.
406 - Client browser does not accept the MIME type of the requested page.
408 - Request timed out.
412 - Precondition failed.
5xx - Server error
These HTTP status codes indicate that the server cannot complete the request because the server encounters an error.

IIS 7.0 uses the following server error HTTP status codes:
500 - Internal server error.

IIS 7.0 defines the following HTTP status codes that indicate a more specific cause of a 500 error:
500.0 - Module or ISAPI error occurred.
500.11 - Application is shutting down on the Web server.
500.12 - Application is busy restarting on the Web server.
500.13 - Web server is too busy.
500.15 - Direct requests for Global.asax are not allowed.
500.19 - Configuration data is invalid.
500.21 - Module not recognized.
500.22 - An ASP.NET httpModules configuration does not apply in Managed Pipeline mode.
500.23 - An ASP.NET httpHandlers configuration does not apply in Managed Pipeline mode.
500.24 - An ASP.NET impersonation configuration does not apply in Managed Pipeline mode.
500.50 - A rewrite error occurred during RQ_BEGIN_REQUEST notification handling. A configuration or inbound rule execution error occurred.
Note Here is where the distributed rules configuration is read for both inbound and outbound rules.
500.51 - A rewrite error occurred during GL_PRE_BEGIN_REQUEST notification handling. A global configuration or global rule execution error occurred.
Note Here is where the global rules configuration is read.
500.52 - A rewrite error occurred during RQ_SEND_RESPONSE notification handling. An outbound rule execution occurred.
500.53 - A rewrite error occurred during RQ_RELEASE_REQUEST_STATE notification handling. An outbound rule execution error occurred. The rule is configured to be executed before the output user cache gets updated.
500.100 - Internal ASP error.
501 - Header values specify a configuration that is not implemented.
502 - Web server received an invalid response while acting as a gateway or proxy.

IIS 7.0 defines the following HTTP status codes that indicate a more specific cause of a 502 error:
502.1 - CGI application timeout.
502.2 - Bad gateway.
503 - Service unavailable.

IIS 7.0 defines the following HTTP status codes that indicate a more specific cause of a 503 error:
503.0 - Application pool unavailable.
503.2 - Concurrent request limit exceeded.

Wednesday, August 21, 2013

Amulyam.in

You can win free mobile recharge with playing games and contests through Amulyam. Go with this link and sign up with amulyam. Amulyam.in