European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: ASP.NET CompareValidator

clock July 21, 2016 20:57 by author Peter

In this article I will show you how to use compare validator to compare the two input values. Using compare validator we can compare two values from two different input controls or we can compare input value with some constant or fixed value.

Example of compare validator:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <ul style="list-style-type: none">
            <li>
                <asp:TextBox ID="txt1" runat="server" />
                =
                <asp:TextBox ID="txt2" runat="server" />
            </li>
            <li>
                <asp:Button ID="Button1" Text="Validate" runat="server" />
            </li>
        </ul>
        <br>
        <asp:CompareValidator ID="compareval" Display="dynamic" ControlToValidate="txt1"
            ControlToCompare="txt2" ForeColor="red" Type="String" EnableClientScript="false"
            Text="Values are not equal." runat="server" />
    </div>
    </form>
</body>
</html>


So in compare validator we need to set ControlToValidate and ControlToCompare in order to compare two input values.

HostForLIFE.eu ASP.NET Core 1.0 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Generate Unique Data in GridView?

clock June 29, 2016 22:02 by author Peter

This time, I will show you how to generate Unique Data in GridView. This code is useful to avoiding data duplicacy in GridView:

HTML of page : EliminateGridview.aspx
<div> 
<h1> 
        Grid with duplicate data 
    </h1> 
<asp:GridView ID="gvDuplicate" runat="server" HeaderStyle-BackColor="gray" 
            AutoGenerateColumns="False" AlternatingRowStyle-BackColor="Yellow " BackColor="white" 
            BorderColor="blue" BorderStyle="None"> 
    <Columns> 
        <asp:BoundField DataField="Name" HeaderText="Name"> 
            <ItemStyle HorizontalAlign="Left" Width="20%" /> 
        </asp:BoundField> 
        <asp:BoundField DataField="City" HeaderText="City"> 
            <HeaderStyle Wrap="true"></HeaderStyle> 
            <ItemStyle HorizontalAlign="Left" Width="20%" Wrap="true" /> 
        </asp:BoundField> 
    </Columns> 
</asp:GridView> 
</div> 
<div> 
<h1> 
        Grid with unique data 
    </h1> 
<asp:GridView ID="gvUnique" runat="server" HeaderStyle-BackColor="gray" AutoGenerateColumns="False" 
            AlternatingRowStyle-BackColor="Yellow " BackColor="white" BorderColor="blue" 
            BorderStyle="None"> 
    <Columns> 
        <asp:BoundField DataField="Name" HeaderText="Name"> 
            <ItemStyle HorizontalAlign="Left" Width="20%" /> 
        </asp:BoundField> 
        <asp:BoundField DataField="City" HeaderText="City"> 
            <HeaderStyle Wrap="true"></HeaderStyle> 
            <ItemStyle HorizontalAlign="Left" Width="20%" Wrap="true" /> 
        </asp:BoundField> 
    </Columns> 
</asp:GridView> 
</div> 

Code behind page: EliminateGridview.aspx.cs

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

public partial class EliminateGridview: System.Web.UI.Page  

protected void Page_Load(object sender, EventArgs e)  

    if (!IsPostBack)  
    { 
        gvDuplicate.DataSource = gvUnique.DataSource = testData(); 
        gvDuplicate.DataBind(); 
        gvUnique.DataBind(); 
        RemoveDuplicateData(0); 
    } 


//generating datatable 
public DataTable testData()  

    DataTable dt = new DataTable(); 
    //Adding columns to datatable        
    dt.Columns.Add("Name"); 
    dt.Columns.Add("City"); 
    //Adding records to the datatable 
    dt.Rows.Add("Peter", "London"); 
    dt.Rows.Add("Peter", "Manchester"); 
    dt.Rows.Add("Peter", "Liverpool"); 
    dt.Rows.Add("Peter", "Bristol"); 
    dt.Rows.Add("Kevin", "Leeds"); 
    dt.Rows.Add("Kevin", "Glasgow"); 
    dt.Rows.Add("Kevin", "York"); 
    dt.Rows.Add("Anthony", "Cambridge"); 
    dt.Rows.Add("Anthony", "Bradford"); 
    dt.Rows.Add("Anthony", "Oxford"); 
    dt.Rows.Add("Steven", "Swansea"); 
    dt.Rows.Add("Richard", "Norwich"); 
    return dt; 

private void RemoveDuplicateData(int cellno)  

    string initialnamevalue = gvUnique.Rows[0].Cells[cellno].Text; 
    for (int i = 1; i < gvUnique.Rows.Count; i++) 
    { 

        if (gvUnique.Rows[i].Cells[cellno].Text == initialnamevalue)  
        { 
            gvUnique.Rows[i].Cells[cellno].Text = string.Empty; 
        }  
        else  
        { 
            initialnamevalue = gvUnique.Rows[i].Cells[cellno].Text; 
        } 
    } 


HostForLIFE.eu ASP.NET Core 1.0 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Send (Pass) multiple parameters to WebMethod in jQuery AJAX POST in ASP.NET?

clock June 23, 2016 22:05 by author Peter

Today let me show you how to send (Pass) multiple parameters to WebMethod in jQuery AJAX POST in ASP.NET. Generally people face issues with jQuery AJAX POST call to WebMethod when multiple parameters have to be passed, due to syntax errors the WebMethod does not get called. Hence I have come up in an innovative way where using JSON object and JSON2 Stringify method one can easily post any number and any type of parameters to WebMethod using jQuery AJAX.

 
HTML Markup
The HTML Markup consists of a sample form with TextBoxes for accepting Name and Age and a Button to post the values to server’s WebMethod using jQuery AJAX.
<table border="0" cellpadding="0" cellspacing="0">
<tr>
    <td>
        Name:
    </td>
    <td>
        <asp:TextBox ID="txtName" runat="server" Text = "Peter" />
    </td>
</tr>
<tr>
    <td>
        Age:
    </td>
    <td>
        <asp:TextBox ID="txtAge" runat="server" Text = "29"/>
    </td>
</tr>
<tr>
    <td>
        <asp:Button ID="btnSubmit" Text="Submit" runat="server" />
    </td>
</tr>
</table>
 
 
WebMethod accepting multiple parameters
The following WebMethod accepts multiple parameters from client side using the jQuery AJAX.
C#
[System.Web.Services.WebMethod]
public static string SendParameters(string name, int age)
{
    return string.Format("Name: {0}{2}Age: {1}", name, age, Environment.NewLine);
}

 
VB.Net
<System.Web.Services.WebMethod()> _
Public Shared Function SendParameters(name As String, age As Integer) As String
    Return String.Format("Name: {0}{2}Password: {1}", name, age, Environment.NewLine)
End Function

 
Passing multiple parameters to WebMethod in jQuery AJAX POST in ASP.Net
When the Button is clicked, the Name and Age is fetched from their respective TextBoxes and are assigned to a JSON object in which I have created two properties with the name same as that of the WebMethod parameters.

The JSON object is now serialized to a JSON string using JSON2 Stringify method and then passed as parameter to the WebMethod.
In this technique there are no syntax errors and also there’s no need to convert values of TextBoxes to integer or some other Data Type.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/json2/20130526/json2.min.js"></script>
<script type="text/javascript">
$(function () {
    $("[id*=btnSubmit]").click(function () {
        var obj = {};
        obj.name = $.trim($("[id*=txtName]").val());
        obj.age = $.trim($("[id*=txtAge]").val());
        $.ajax({
            type: "POST",
            url: "CS.aspx/SendParameters",
            data: JSON.stringify(obj),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                alert(r.d);
            }
        });
        return false;
    });
});
</script>

HostForLIFE.eu ASP.NET 4.6 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Handle Error 404?

clock April 22, 2016 23:19 by author Anthony

404 is a frequently-seen status code that tells a Web user that a requested page is "Not found." 404 and other status codes are part of the Web's Hypertext Transfer Protocol ( HTTP ), written in 1992 by the Web's inventor, Tim Berners-Lee. He took many of the status codes from the earlier Internet protocol for transferring files, the File Transfer Protocol ( FTP .)

What to Do If You Get a 404

If the site no longer exists, there's nothing you can do. However, it only takes one mistyped character to result in a 404. See whether the ".htm" should be an ".html" or vice versa. If you're linking from a Web site, you can do a "View source" to make sure it wasn't miscoded. Whether or not it is, you may want to send a note to the Webmaster so that the link can be fixed for the next users.

In this tutorial, I will show you how to handle 404 error in ASP.NET Core 1.0. Prior versions of ASP.NET Core 1.0, have custom errors for error handling. With ASP.NET Core 1.0 and MVC, you can do the error handling via Middlwares. HTTP 404 is a very common error which comes when server can’t find the requested resource. In this post, we will see different ways to handle HTTP 404 error in ASP.NET Core 1.0 and MVC.

How to handle 404 error in ASP.NET Core 1.0


I found 2 ways to handle 404 error. In fact using these solution you can handle any HTTP status code errors. To handle the error, both the solution are using configure() method of Startup.cs class. For those who are not aware about Startup.cs, it is entry point for application itself. You can read this excellent post The Startup.cs File in ASP.NET Core 1.0. to know more about startup.cs. And within the startup.cs file, you will also find static void main() which generally you use with windows/console applications. Read my post Why static void main in ASP.NET 5 startup.cs

Now coming back to our solution 1, within configure method define a custom middleware via app.Use which checks for status code value in response object. And if is 404 then it redirects to Home controller.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
 
    app.UseApplicationInsightsRequestTelemetry();
    app.Use(async (context, next) =>
    {
        await next();
        if (context.Response.StatusCode == 404)
        {
            context.Request.Path = "/Home";
            await next();
        }
    });
 
    app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
    app.UseApplicationInsightsExceptionTelemetry();
    app.UseStaticFiles();
    app.UseIdentity();
    // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Solution 2

The other solution is to use a built-in middlware StatusCodePagesMiddleware. This middleware can be used to handle the response status code is between 400 and 600. This middleware allows to return a generic error response or allows you to also redirect to another middle. See below all different variations of this middleware.

app.UseStatusCodePages();
 
// app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
// app.UseStatusCodePages("text/plain", "Response, status code: {0}");
// app.UseStatusCodePagesWithRedirects("~/errors/{0}"); // PathBase relative
// app.UseStatusCodePagesWithRedirects("/base/errors/{0}"); // Absolute
// app.UseStatusCodePages(builder => builder.UseWelcomePage());
// app.UseStatusCodePagesWithReExecute("/errors/{0}");

Now to handle the 404 error, we shall use app.UseStatusCodePagesWithReExecute which accepts a path where you wish to redirect.

app.UseStatusCodePagesWithReExecute("/Home/Errors/{0}");

So we are redirecting here to Home Controller and Errors action method. The {0} is nothing but the HTTP status error code. Below is the implementation of Errors action method.

public IActionResult Errors(string errCode)
{
    ViewData["ErrorID"] = "The following error " + errCode + " occured";
    return View("~/Views/Shared/Error.cshtml");
}

It adds the status code in ViewData and then returns to Error.cshtml shared view. You can also return to specific error page based on the error code.

public IActionResult Errors(string errCode)
{
  if (errCode == "500" | errCode == "404")
  {
    return View($"~/Views/Home/Error/{errCode}.cshtml");
  }
 
  return View("~/Views/Shared/Error.cshtml");
}

So, if the error code is 500 or 404 then return to Home/Error/500.cshtml or 404.cshtml.

You must have seen on many websites, forums about app.UseErrorPage(); to handle the errors. But this is no longer available with RC1 release of ASP.NET Core 1.0. This was available until beta 5 or 6.


HostForLIFE.eu ASP.NET Core 1.0 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Check Record Availability using JOSN and jQuery?

clock April 20, 2016 00:10 by author Peter

In this tutorial, I will show you how to Check Record Availability using JOSN and jQuery. I will check user name available or not a table without refreshing the page using JOSN in ASP.NET. The followind code will explains how to check the user name that end user is entering already exist in database or not if it exist then message will show. In this entire process page is not refreshing.


I am using JOSN and Ajax as in the following example:   

<script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>  
    <script type = "text/javascript"> 
    function ShowAvailability() { 
        $.ajax({ 
            type: "POST", 
            url: "CheckUserAvalibleusingJOSN.aspx/CheckUserName", 
            data: '{userName: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }', 
            contentType: "application/json; charset=utf-8", 
            dataType: "json", 
            success: OnSuccess, 
            failure: function (response) { 
                alert(response); 
            } 
        }); 
    } 
     
    function OnSuccess(response) { 
        var mesg = $("#mesg")[0]; 
        switch (response.d) { 
            case "true": 
            mesg.style.color = "green"; 
            mesg.innerHTML = "Available"; 
            break; 
            case "false": 
            mesg.style.color = "red"; 
            mesg.innerHTML = "Not Available"; 
            break; 
            case "error": 
            mesg.style.color = "red"; 
            mesg.innerHTML = "Error occured"; 
            break; 
        } 
    } 
     
    function OnChange(txt) { 
        $("#mesg")[0].innerHTML = ""; 
        ShowAvailability();//hide this function from here if we want to check avability by using button click 
    } 
    </script> 
    </head> 
    <body> 
        <form id="form1" runat="server"> 
        <div > 
            UserName : <asp:TextBox ID="txtUserName" runat="server" onkeyup = "OnChange(this)"></asp:TextBox> 
            <%--<input id="btnCheck" type="button" value="Show Availability" onclick = "ShowAvailability()" />--%> 
            <br /> 
            <span id = "mesg"></span> 
            </div> 
        </form> 
    </body>


Code

    [System.Web.Services.WebMethod] 
    public static string CheckUserName(string userName) 
    { 
        string returnValue = string.Empty; 
        try 
        { 
            string consString = ConfigurationManager.ConnectionStrings["manish_dbCS"].ConnectionString; 
            SqlConnection conn = new SqlConnection(consString); 
            SqlCommand cmd = new SqlCommand("spx_CheckUserAvailability", conn); 
            cmd.CommandType = CommandType.StoredProcedure; 
            cmd.Parameters.AddWithValue("@UserName", userName.Trim()); 
            conn.Open(); 
            returnValue = cmd.ExecuteScalar().ToString(); 
            conn.Close(); 
        } 
        catch 
        { 
            returnValue = "error"; 
        } 
        return returnValue; 
    }


SQL Query

    USE [manish_db] 
    GO 
    /****** Object: StoredProcedure [dbo].[spx_CheckUserAvailability] Script Date: 07/19/2014 02:17:13 ******/ 
    SET ANSI_NULLS ON 
    GO 
    SET QUOTED_IDENTIFIER ON 
    GO 
    ALTER PROCEDURE [dbo].[spx_CheckUserAvailability] 
    @UserName VARCHAR(50) 
    AS 
    BEGIN 
    SET NOCOUNT ON; 
    IF NOT EXISTS 
    (SELECT UserName FROM dbo.UserDetails 
    WHERE UserName = @UserName 
    ) 
    SELECT 'true' 
    ELSE 
    SELECT 'false' 
    END

Note: If we use web services just add webservices and replace the page path with *.asmx file path.

Code

    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService] 
    public class CheckUserAvalible : System.Web.Services.WebService 
    { 
        [WebMethod] 
        public string CheckUserName(string userName) 
        { 
            string returnValue = string.Empty; 
            try 
            { 
                string consString = ConfigurationManager.ConnectionStrings["manish_dbCS"].ConnectionString; 
                SqlConnection conn = new SqlConnection(consString); 
                SqlCommand cmd = new SqlCommand("spx_CheckUserAvailability", conn); 
                cmd.CommandType = CommandType.StoredProcedure; 
                cmd.Parameters.AddWithValue("@UserName", userName.Trim()); 
                conn.Open(); 
                returnValue = cmd.ExecuteScalar().ToString(); 
                conn.Close(); 
            } 
            catch 
            { 
                returnValue = "error"; 
            } 
            return returnValue; 
        } 
    }


I Hope it works for you! Happy coding.

HostForLIFE.eu ASP.NET Core 1.0 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Select Data Tree View in ASP.NET ?

clock April 12, 2016 20:44 by author Peter

Today, let me show you how to select data tree view in ASP.NET. The ASP.NET TreeView control is a powerful server-control for rendering TreeView UI, as shown in the figure below. It supports a variety of programming models, from statically-defined trees, to dynamically constructed trees, to databound trees. The TreeView's rendering is fully customizable, allowing for a wide-range of look-and-feels for the control. The TreeView supports both postback-style events and simple hyperlink navigation, as well as a unique event handling model that allows data to be retrieved directly from a client without requiring a server postback. It also supports rendering on a variety of browsers, and can take advantage of up-level capabilities, such as client-script on later desktop browser versions.


Now, it's time to write the following code:
    public void fill() 
    { 
        con.Open(); 
        SqlCommand cmd = new SqlCommand("select sr_no,rank_no,emp_name,emp_code,rank_name,doj from empregistration where emp_code='" + TextBox4.Text + "' ", con); 
        SqlDataReader dr = cmd.ExecuteReader(); 
        if (dr.Read())  
        { 
            no = Convert.ToInt32(dr["rank_no"].ToString()); 
            Label20.Text = dr["emp_name"].ToString(); 
            Label21.Text = dr["emp_code"].ToString(); 
            Label22.Text = dr["rank_name"].ToString(); 
            Label23.Text = dr["doj"].ToString(); 
            no13 = Convert.ToInt32(dr["sr_no"].ToString()); 
            dr.Read(); 
        } else  
        { 
            Response.Write("<script>alert('Employee Code Is Not Correct')</script>"); 
        } 
        for (int i = no; i >= 1; i--)  
        { 
            if (i == 12) 
            { 
                no12 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 11) 
            { 
                no11 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 10)  
            { 
                no10 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 9) 
            { 
                no9 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 8)  
            { 
                no8 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 7) 
            { 
                no7 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 6)  
            { 
                no6 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 5)  
            { 
                no5 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 4) 
            { 
                no4 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 3) 
            { 
                no3 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 2) 
            { 
                no2 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 1) 
            { 
                no1 = Convert.ToInt32(i.ToString()); 
            } 
        } 
        con.Close(); 
        // SqlCommand cmd1 = new SqlCommand("select rank_no from empregistration where ", con); 
    } 
    protected void Button1_Click(object sender, EventArgs e)  
    { 
        Label14.Visible = true; 
        Label8.Visible = true; 
        Label15.Visible = false; 
        Label7.Visible = false; 
        fill(); 
        con.Open(); 
        SqlCommand cmd = new SqlCommand("select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no12 + "'and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no11 + "' and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no10 + "' and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no9 + "'and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no8 + "' and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no7 + "' and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no6 + "'and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no5 + "'and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no4 + "' and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no3 + "' and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no2 + "' and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no1 + "' and sr_no >'" + no13.ToString() + "' order by emp_code asc ", con); 
        SqlDataAdapter da = new SqlDataAdapter(cmd); 
        DataSet ds = new DataSet(); 
        da.Fill(ds); 
        if (ds.Tables[0].Rows.Count > 0) 
        { 
            gvProducts.DataSource = ds; 
            gvProducts.DataBind(); 
        } 
        con.Close(); 
    } 


I hope this code is work for you. Good luck!

 

HostForLIFE.eu ASP.NET Core 1.0 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Get Youtube Video Thumbnail image in ASP.NET?

clock March 31, 2016 23:15 by author Peter

This tutorial will show you how to get youtube video thumbnail image in ASP.NET. Write the following code that returns image thumbnail url of given youtube video url by passing video url as a parameter in getYouTubeThumbnail method.

public string getYouTubeThumbnail(string YoutubeUrl)   
{   
    string youTubeThumb=string.Empty;   
    if (YoutubeUrl == "")   
        return "";   
 
    if (YoutubeUrl.IndexOf("=") > 0)   
    {   
        youTubeThumb = YoutubeUrl.Split('=')[1];   
    }   
    else if (YoutubeUrl.IndexOf("/v/") > 0)   
    {   
        string strVideoCode = YoutubeUrl.Substring(YoutubeUrl.IndexOf("/v/") + 3);   
        int ind = strVideoCode.IndexOf("?");   
        youTubeThumb = strVideoCode.Substring(0, ind == -1 ? strVideoCode.Length : ind);   
    }   
    else if (YoutubeUrl.IndexOf('/') < 6)   
    {   
        youTubeThumb = YoutubeUrl.Split('/')[3];   
    }   
    else if (YoutubeUrl.IndexOf('/') > 6)   
    {   
        youTubeThumb = YoutubeUrl.Split('/')[1];   
    }   
 
    return "http://img.youtube.com/vi/" + youTubeThumb + "/mqdefault.jpg";   
}   

You may call the above function with various youtube url format like,
getYouTubeThumbnail("http://youtu.be/4e3qaPg_keg");   
getYouTubeThumbnail("http://www.youtube.com/watch?v=bvLaTupw-hk");

HostForLIFE.eu ASP.NET Core 1.0 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Upload File to SFTP Server using free Utility WINSCP?

clock March 2, 2016 21:45 by author Peter

In this tutorial, I will describe a technique for uploading a file to sftp server using third party tools WinSCP. WinSCP is an open source free SFTP client, FTP client, WebDAV client and SCP client for Windows. Its main function is file transfer between a local and a remote computer. Beyond this, WinSCP offers scripting and basic file manager functionality.

Features

  • Graphical user interface
  • Translated into many languages
  • Integration with Windows (drag&drop, URL, shortcut icons, jump list)
  • All common operations with files
  • Support for SFTP and SCP protocols over SSH and FTP and WebDAV protocols
  • Batch file scripting and command-line interface and .NET assembly for advanced programming tasks
  • Directory synchronization in several semi or fully automatic ways
  • Integrated text editor
  • Shares site settings with PuTTY
  • Support for password, keyboard-interactive, public key and Kerberos (GSS) authentication
  • Integrates with Pageant (PuTTY authentication agent) for full support of public key authentication with SSH
  • Explorer and Commander interfaces
  • Optionally protects stored site information with master password
  • Optionally supports portable operation using a configuration file in place of registry entries, suitable for operation from removable media

Now, write the following code:
private static void UploadToSFTP(string stringJasontext) 

try 

    //get static value from App.config file. 
    string ftpServerIP = ConfigurationSettings.AppSettings["sftpServerIP"].ToString(); 
    string stringsFtpUserID = ConfigurationSettings.AppSettings["sftpUserID"].ToString(); 
    string stringsFtpPassword = ConfigurationSettings.AppSettings["sftpPassword"].ToString(); 
    string stringStrDate = System.DateTime.Now.ToString("dd_MM_yyyy-hh_mm_ss"); 
    string stringFileName = "LeaseJson_" + stringStrDate + ".json"; 
    string stringFromPath = ConfigurationSettings.AppSettings["sFromPath"].ToString(); 
    string stringToPath = ConfigurationSettings.AppSettings["sToPath"].ToString(); 
    string stringHostKey = ConfigurationSettings.AppSettings["sHostKey"].ToString(); 
    string stringsBackUpFolder = "Processed"; 
    //create folder for back up data 
    if (!Directory.Exists(stringFromPath + stringsBackUpFolder)) 
    { 
          Directory.CreateDirectory(stringFromPath + stringsBackUpFolder); 
    } 
    //check whether file exist or not in local machine. 
    if (!System.IO.File.Exists(stringFromPath + stringFileName)) 
    { 
          using (FileStream fileStreamLocalFile = File.Create(stringFromPath + stringFileName)) 
          { 
                byte[] byteLocalFile = new UTF8Encoding(true).GetBytes(stringJasontext); 
                fileStreamLocalFile.Write(byteLocalFile, 0, byteLocalFile.Length); 
          } 
    } 
    SessionOptions sessionOptionsSFTP = new SessionOptions 
    { 
          Protocol = Protocol.Sftp, 
          HostName = ftpServerIP, 
          UserName = stringsFtpUserID, 
          Password = stringsFtpPassword, 
          PortNumber = 22, 
          SshHostKeyFingerprint = stringHostKey 
    }; 
    WinSCP.Session sessionSFTP = new WinSCP.Session(); 
    sessionSFTP.Open(sessionOptionsSFTP); 
    TransferOptions transferOptionsSFTP = new TransferOptions(); 
    transferOptionsSFTP.TransferMode = TransferMode.Binary; 
    transferOptionsSFTP.FilePermissions = null; 
    transferOptionsSFTP.PreserveTimestamp = false; 
    transferOptionsSFTP.ResumeSupport.State = TransferResumeSupportState.Off; 
    TransferOperationResult transferOperationResultSFTP; 
    transferOperationResultSFTP = sessionSFTP.PutFiles(stringFromPath + stringFileName, stringToPath, false, transferOptionsSFTP); 
    if (System.IO.File.Exists(stringFromPath + stringFileName)) 
    { 
          File.Move(stringFromPath + stringFileName, stringFromPath + "\\" + stringsBackUpFolder + "\\" + stringFileName); 
    } 
    transferOperationResultSFTP.Check();

    if (transferOperationResultSFTP.IsSuccess == true) 
    { 
          Console.Write("File upload successfully"); 
    } 
    else 
    { 
          Console.Write("File upload failed"); 
    } 


catch (Exception exError) 

    Console.Write(exError.Message); 


#endregion 
#region Upload File to FTP server as Json File 
//private static void UploadToFTP(string stringJasontext) 
//{ 
// try 
// { 
// string stringFtpUserID = ConfigurationSettings.AppSettings["ftpUserID"].ToString(); 
// string stringFtpPassword = ConfigurationSettings.AppSettings["ftpPassword"].ToString(); 
// string stringStrDate = System.DateTime.Now.ToString("dd_MM_yyyy-hh_mm"); 
// string stringToPath = ConfigurationSettings.AppSettings["ToPath"].ToString() + "LeaseJson_" + stringStrDate + ".json"; 
// FtpWebRequest ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(stringToPath); 
// ftpWebRequest.Credentials = new NetworkCredential(stringFtpUserID, stringFtpPassword); 
// ftpWebRequest.KeepAlive = false; 
// ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile; 
// ftpWebRequest.UseBinary = true; 
// ftpWebRequest.ContentLength = stringJasontext.Length; 
// ftpWebRequest.Proxy = null; 
// using (Stream TempStream = ftpWebRequest.GetRequestStream()) 
// { 
// System.Text.ASCIIEncoding TempEncoding = new System.Text.ASCIIEncoding(); 
// byte[] byteTempBytes = TempEncoding.GetBytes(stringJasontext); 
// TempStream.Write(byteTempBytes, 0, byteTempBytes.Length); 
// } 
// ftpWebRequest.GetResponse(); 
// } 
// catch (Exception exError) 
// { 
// Console.Write(exError.Message); 
// } 
//} 
#endregion 

 

HostForLIFE.eu ASP.NET Core 1.0 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Make all Child Check Boxes checked on Master Check Box Checked Event ?

clock February 24, 2016 19:43 by author Peter

This code for how to Make all Child Check Boxes checked on Master Check Box Checked Event. Checkboxes allow the user to select one or more options from a set. Typically, you should present each checkbox option in a vertical list. Now write the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title></title> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div style="height:70%;width:70%"> 
<asp:GridView ID="gridview1" runat="server" AutoGenerateColumns="False"  
DataKeyNames="ID" DataSourceID="SqlDataSource1" BackColor="White"  
BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3"  
GridLines="Horizontal" Width="100%"> 
<AlternatingRowStyle BackColor="#F7F7F7" /> 
<Columns> 
<asp:TemplateField> 
<HeaderTemplate> 
    <asp:CheckBox ID="CheckBox2" onclick="headercheckbox(this);" runat="server" /> 
</HeaderTemplate> 
<ItemTemplate> 
    <asp:CheckBox ID="CheckBox1" onclick="childcheckboxes(this);" runat="server" /> 
</ItemTemplate> 
</asp:TemplateField> 
<asp:TemplateField> 
<HeaderTemplate> 
    <asp:LinkButton ID="LinkButton1" runat="server">Delete</asp:LinkButton> 
</HeaderTemplate> 
<ItemTemplate> 
    <asp:LinkButton ID="LinkButton2" runat="server">Delete</asp:LinkButton> 
</ItemTemplate> 
</asp:TemplateField> 
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"  
ReadOnly="True" SortExpression="ID" /> 
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" /> 
<asp:BoundField DataField="Class" HeaderText="Class" SortExpression="Class" /> 
<asp:BoundField DataField="Lastname" HeaderText="Lastname"  
SortExpression="Lastname" /> 
</Columns> 


<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" /> 
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" /> 
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" /> 
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" /> 
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" /> 
<SortedAscendingCellStyle BackColor="#F4F4FD" /> 
<SortedAscendingHeaderStyle BackColor="#5A4C9D" /> 
<SortedDescendingCellStyle BackColor="#D8D8F0" /> 
<SortedDescendingHeaderStyle BackColor="#3E3277" /> 


</asp:GridView> 
<asp:SqlDataSource ID="SqlDataSource1" runat="server"  
ConnectionString="<%$ ConnectionStrings:akConnectionString %>"  
SelectCommand="SELECT [ID], [Name], [Class], [Lastname] FROM [nametb]"> 
</asp:SqlDataSource> 

<script type="text/javascript" language="javascript"> 
var gridview = document.getElementById("gridview1"); 
function headercheckbox(checkbox) { 
for (var i = 1; i < gridview.rows.length; i++)  

  gridview.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked = checkbox.checked; 


function childcheckboxes(checkbox) { 
  var atleastekcheck = false; 
  for (var i = 1; i < gridview.rows.length; i++)  
  { 
      if (gridview.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked == false)  
      { 
          atleastekcheck = true; 
          break; 
      } 
      
  } 
   gridview.rows[0].cells[0].getElementsByTagName("INPUT")[0].checked = !atleastekcheck  ; 


</script> 

HostForLIFE.eu ASP.NET Core 1.0 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in