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 :: 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. 



ASP.NET 5 Hosting - HostForLIFE.eu :: Recursive FindControl & Extension Methods

clock February 17, 2016 21:20 by author Peter

Here's a really short and easy little bit of code that has the potential to be slightly of a time-saver. The FindControl method of the control class is used to find a specific child control of a given parent, searching by ID. This method, however, does not search the control hierarchy recursively: it searches the direct children of the specified parent control only. While writing a recursive version of this method is trivial, a rather nice way to make the technique reusable is to implement it as an extension method. Here's how it can be done:

//search the children
foreach (Control child in control.Controls)
{
    ctrl = FindControlRecursive(child, id);
    if (ctrl != null) break;
}
}

return ctrl;
}

}
}


And to call it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using Boo.Web.UI.Extensions;

namespace MyWebApp
{
public partial class WebForm1 : System.Web.UI.Page

{
    public void Page_Load(object sender, EventArgs e)
    {
       //call the recursive FindControl method
        Control ctrl = this.FindControlRecursive("my_control_id");
    }
}
}


Now, don't forget to import the namespace within which the extensions method class is declared- or a compilation error will not long follow. Now, all you need to do is import this same namespace for any pages/user controls/custom controls which need to use the recursive control search and you're good to go.

Doing it this way is of course logically no different to creating a static method in a util class, and passing both the parent control and the ID of the child control you want to find to it, but considering how commonly this functionality is required, it's nice to be able to tack it onto the control class itself, and extension methods provide an elegant way to accomplish this.

HostForLIFE.eu ASP.NET 4.6 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 4.6 Hosting - HostForLIFE.eu :: How to Use FileUpload in ASP.NET, How to Save Image , Picture in Website Folder?

clock February 3, 2016 19:24 by author Peter

First we  craete  a  table UserImage using database test:
use test
create  table UserImage(SrNo int  primary key,Name nvarchar(50),UserImg nvarchar(max))

After than we  create  a Web from  like  this and  take  a Folder Image  in our  WebSite  for  saving  image  which are  upload  by  user.

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>
<style type="text/css">
.style1 {
    width: 100%;
}
.style2
{
    width: 351px;
}
</style>
</head>
<body>

<form id="form1" runat="server">
<div>
<table class="style1">
<tr>
    <td colspan="3"><center><asp:Label ID="Label1" runat="server" Text="Save Image in Image folder and Database" Font-Bold="true"></asp:Label></center>
      
    </td>
</tr>
<tr>
    <td>
        <asp:Label ID="SrNo" runat="server" Text="SrNo"></asp:Label>
    </td>
    <td class="style2">
        <asp:TextBox ID="txtsrno" runat="server"></asp:TextBox>
    </td>
    <td rowspan="5">
        <asp:Image ID="Image1" runat="server" Height="91px" Width="99px" />
    </td>
</tr>
<tr>
    <td>
        <asp:Label ID="Label4" runat="server" Text="Name"></asp:Label>
    </td>
    <td class="style2">
        <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
    </td>
</tr>
<tr>
    <td>
        <asp:Label ID="Label5" runat="server" Text="Image"></asp:Label>
    </td>
    <td class="style2">
        <asp:FileUpload ID="FileUpload1" runat="server" />
    </td>
</tr>
<tr>
    <td>
        &nbsp;</td>
    <td class="style2">

        <asp:Button ID="BSave" runat="server" onclick="BSave_Click" Text="Save" />
    <asp:Button ID="BSelect" runat="server" onclick="BSelect_Click" Text="Select" />
        <asp:Button ID="BDelete" runat="server" onclick="BDelete_Click" Text="Delete" />
&nbsp;<asp:Button ID="BUpdate" runat="server" onclick="BUpdate_Click" Text="Update" />
    </td>
</tr>
<tr>
    <td>
        &nbsp;</td>
    <td class="style2">
        <asp:Label ID="Message" runat="server" Text="Label" Visible="False"></asp:Label>
    </td>
</tr>
</table>
</div>
</form>
</body>
</html>


Now we create Connection global for Website in web.config
<configuration>
<connectionStrings>
<add name="kush" connectionString="Data Source=KUSH-PC; Initial Catalog=test;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
</configuration>


Default.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.SqlClient;
using System.Configuration;

//Using this namespace for DirectoryInfo and FileInfo
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["kush"].ConnectionString);
}
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
//Saving image in Database and Image Folder which are exist in Website
protected void BSave_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("insert into UserImage (SrNo,Name,UserImg) values (@SrNo,@Name,@UserImg)", con);
cmd.Parameters.AddWithValue("@SrNo", Convert.ToInt32(txtsrno.Text));
cmd.Parameters.AddWithValue("@Name", txtname.Text);
cmd.Parameters.AddWithValue("@UserImg", FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/Image/") + FileUpload1.FileName);
cmd.ExecuteNonQuery();
 Message.Visible=true;
Message.Text = "Add Successfully ";
con.Close();
txtname.Text = "";
}
//retrive image  from Database  and  Image Folder which are exist  in Website
protected void BSelect_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("select * from UserImage where SrNo=@SrNo", con);
cmd.Parameters.AddWithValue("@SrNo", Convert.ToInt32(txtsrno.Text));
 dr=cmd.ExecuteReader();
 if (dr.Read())
 {
     txtname.Text = dr["Name"].ToString();
     Image1.ImageUrl = "~/Image/" + dr["UserImg"].ToString();
 }
con.Close();
}

//The following code is for  delete image  from  Database  and  Image Folder which are exist  in  Website
protected void BDelete_Click(object sender, EventArgs e)
{
DirectoryInfo dd = new DirectoryInfo(Server.MapPath("~/Image"));
foreach (FileInfo ff in dd.GetFiles())
{
    if (ff.Name == Path.GetFileName(Image1.ImageUrl))
        ff.Delete();
}

 con.Open();
 cmd = new SqlCommand("delete from UserImage where SrNo=@SrNo", con);
 cmd.Parameters.AddWithValue("@SrNo", Convert.ToInt32(txtsrno.Text));
 cmd.ExecuteNonQuery();
 con.Close();
 txtname.Text = "";
 Message.Visible=true;
 Message.Text="Delete Successfully Image "+"For SrNo"+"-"+txtsrno.Text+"";
}

//this  code  for  Update  image  in Database  and  Image Folder and  old  image  deleted  from Image Folder

protected void BUpdate_Click(object sender, EventArgs e)
{
try
{

    DirectoryInfo dd = new DirectoryInfo(Server.MapPath("~/Image"));
    foreach (FileInfo ff in dd.GetFiles())
    {
        if (ff.Name == Path.GetFileName(Image1.ImageUrl))
            ff.Delete();
    }

    con.Open();
    cmd = new SqlCommand("update  UserImage set Name=@Name, UserImg=@UserImg  where SrNo=@SrNo", con);
    cmd.Parameters.AddWithValue("@SrNo", Convert.ToInt32(txtsrno.Text));
    cmd.Parameters.AddWithValue("@Name", txtname.Text);
    if (FileUpload1.HasFile)
    {
        cmd.Parameters.AddWithValue("@UserImg", FileUpload1.FileName);
    }
    else
    {
        cmd.Parameters.AddWithValue("@UserImg", Image1.ImageUrl);
    }

    FileUpload1.SaveAs(Server.MapPath("~/Image/") + FileUpload1.FileName);
    cmd.ExecuteNonQuery();
    con.Close();
    txtname.Text = "";
    Message.Visible = true;
    Message.Text = "update Successfully Image " + "For SrNo" + "-" + txtsrno.Text + "";
}
catch (Exception ex)
{
    Message.Visible = true;
    Message.Text = ex.Message;
}

}
}

HostForLIFE.eu ASP.NET 4.6 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 4.6 Hosting - HostForLIFE.eu :: How to Make a Text Chat in ASP.Net?

clock January 20, 2016 20:40 by author Peter

Now, Making Text Chat in ASP.NET Application is now easy. I am using Jaxter Chat Control. JaxterChat is an effective tool for nurturing online communities within your website. By combining the rapid response of ajax with the power and flexibility os ASP.NET, JaxterChat provides a stylish alternative to traditional Flash and Java chat clients. JaxterChat supports a rich designer interface for previewing the appearance of the control at design time. Display properties can be adjusted and the effects of these changes are reflected instantly in the Visual Studio designer view.

We are going to working with Text Chat using Jaxter Chat control in ASP.NET.  Now, write the following code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> 
<%@ Register assembly="JaxterChat" namespace="WebFurbish" tagprefix="cc1" %> 
<!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 style="height: 316px"> 
<form id="form1" runat="server"> 
<div> 
    <cc1:JaxterChat ID="JaxterChat1" runat="server" BackColor="#A0AB9D" BackImageUrl="JaxterChat/Themes/Googleish/back_strip_4.jpg" ClearPageButtonImageUrl="JaxterChat/Images/clear_page.gif" EmoticonsButtonImageUrl="JaxterChat/Images/emoticons.gif" FontColor="MidnightBlue" FontFace="Arial, Verdana" FontSizePixels="12" FooterPanelHeightPixels="0" HeaderPanelHeightPixels="23" Height="300px" MessageInputBackColor="White" MessageInputBorderColor="DarkGray" MessageInputBorderWidthPixels="1" MessageInputFontColor="Black" MessageInputFontFace="Arial, Verdana" MessageInputFontSizePixels="12" MessageInputHeightPixels="38" MessageInputPaddingBottomPixels="1" MessageInputPaddingLeftPixels="1" MessageInputPaddingRightPixels="1" MessageInputPaddingTopPixels="1" MessageOutputBackColor="White" MessageOutputBorderColor="DarkGray" MessageOutputBorderWidthPixels="1" MessageOutputFontColor="Black" MessageOutputFontFace="Arial, Verdana" MessageOutputFontSizePixels="12" MessageOutputLinkColor="90, 128, 198" MessageOutputPaddingBottomPixels="1" MessageOutputPaddingLeftPixels="8" MessageOutputPaddingRightPixels="1" MessageOutputPaddingTopPixels="2" MessageOutputPostIconUrl="JaxterChat/Themes/Googleish/icon.gif" MessageOutputUserNameFontColor="Black" PaddingBottomPixels="5" PaddingLeftPixels="4" PaddingRightPixels="4" PaddingTopPixels="3" PopupCloseButtonImageUrl="JaxterChat/Images/popup_close.gif" PopupWindowBackColor="Gainsboro" PopupWindowContentFontColor="Black" PopupWindowContentFontFace="Arial, Verdana" PopupWindowContentFontSizePixels="10" PopupWindowTitleFontColor="Black" PopupWindowTitleFontFace="Arial, Verdana" PopupWindowTitleFontSizePixels="12" ScrollBarIE3DLightColor="White" ScrollBarIEArrowColor="LightGray" ScrollBarIEBaseColor="Silver" ScrollBarIEDarkShadowColor="Silver" ScrollBarIEFaceColor="White" ScrollBarIEHighlightColor="AliceBlue" ScrollBarIEShadowColor="Silver" ScrollBarIETrackColor="Gainsboro" SendButtonImageUrl="JaxterChat/Images/send_button.gif" ShowSendButton="False" ToggleSoundOffButtonImageUrl="JaxterChat/Images/sound_off.gif" ToggleSoundOnButtonImageUrl="JaxterChat/Images/sound_on.gif" ToolbarPanelHeightPixels="21" UserListButtonImageUrl="JaxterChat/Images/users.gif" Width="359px"> 
    </cc1:JaxterChat> 
    <br /> 
</div> 
</form> 
</body> 
</html> 

HostForLIFE.eu ASP.NET 4.6 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 4.6 Hosting - HostForLIFE.eu :: How to Fixing the Error logging and Exception handling?

clock January 6, 2016 21:10 by author Peter

The errors and exceptions are going to be written to a text file because it is simpler to search out the reason for the error because the Error Log text file are often easily opened using the basic notepad application in Windows.

The following HTML Markup consists of an ASP.NET Button control which will raise an Exception and the exception (error) Message details will be displayed.
<asp:Button Text="Click to Raise Exception" runat="server" OnClick="RaiseException"/>

Namespaces
You will need to import the following namespace.
C#
using System.IO;

VB.Net
Imports System.IO

Creating simple Error Log Text File in ASP.NET
The following event handler is raised when the Button is clicked. An exception is raised by converting a string value to integer inside a Try-Catch block.
The raised Exception is caught in the Catch block and the LogError function is called.
Inside the LogError function, the details of the exception (error) are written to an Error Log Text file along with current date and time.


C#
protected void RaiseException(object sender, EventArgs e)
{
try
{
    int i = int.Parse("Mudassar");
}
catch (Exception ex)
{
    this.LogError(ex);
}
}

private void LogError(Exception ex)
{
string message = string.Format("Time: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
message += Environment.NewLine;
message += "-----------------------------------------------------------";
message += Environment.NewLine;
message += string.Format("Message: {0}", ex.Message);
message += Environment.NewLine;
message += string.Format("StackTrace: {0}", ex.StackTrace);
message += Environment.NewLine;
message += string.Format("Source: {0}", ex.Source);
message += Environment.NewLine;
message += string.Format("TargetSite: {0}", ex.TargetSite.ToString());
message += Environment.NewLine;
message += "-----------------------------------------------------------";
message += Environment.NewLine;
string path = Server.MapPath("~/ErrorLog/ErrorLog.txt");
using (StreamWriter writer = new StreamWriter(path, true))
{
    writer.WriteLine(message);
    writer.Close();
}
}


VB.Net
Protected Sub RaiseException(sender As Object, e As EventArgs)
Try
    Dim i As Integer = Integer.Parse("Mudassar")
Catch ex As Exception
    Me.LogError(ex)
End Try
End Sub

Private Sub LogError(ex As Exception)
Dim message As String = String.Format("Time: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"))
message += Environment.NewLine
message += "-----------------------------------------------------------"
message += Environment.NewLine
message += String.Format("Message: {0}", ex.Message)
message += Environment.NewLine
message += String.Format("StackTrace: {0}", ex.StackTrace)
message += Environment.NewLine
message += String.Format("Source: {0}", ex.Source)
message += Environment.NewLine
message += String.Format("TargetSite: {0}", ex.TargetSite.ToString())
message += Environment.NewLine
message += "-----------------------------------------------------------"
message += Environment.NewLine
Dim path As String = Server.MapPath("~/ErrorLog/ErrorLog.txt")
Using writer As New StreamWriter(path, True)
    writer.WriteLine(message)
    writer.Close()
End Using
End Sub

And here is the output:

HostForLIFE.eu ASP.NET 4.6 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 4.6 Hosting - HostForLIFE.eu :: How to Edit value of RequiresQuestionAndAnswer in ASP.NET 4.6 Membership Provider

clock October 29, 2015 01:16 by author Peter

Let me show you how to edit value of RequiresQuestionAndAnswer in ASP.NET 4.6 Membership provider. RequiresQuestionAndAnswer is checked when ResetPassword or GetPassword is called. The provider provided with the .NET Framework throws a NotSupportedException if RequiresQuestionAndAnswer is true and the supplied password answer is null. Requiring a password question and answer provides an additional layer of security when retrieving or resetting a user's password. Users can supply a question and answer when their user name is created that they can later use to retrieve or reset a forgotten password.

A Membership Provider allows a web application to store and retrieve membership data for a user, and the standard ASP.NET Membership Provider uses pre-defined SQL Server tables.

Now you write the following example code:
MembershipUser user = Membership.GetUser();
string newPassword = "newPass";
string tempPassword = string.Empty;
if (Membership.Provider.RequiresQuestionAndAnswer)
{
var _requiresQA = Membership.Provider.GetType().GetField("_RequiresQuestionAndAnswer",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
//change the value in the private field
_requiresQA.SetValue(Membership.Provider, false);
//do the reset
tempPassword = user.ResetPassword();
//set it's original value
_requiresQA.SetValue(Membership.Provider, true);
}
else
{
tempPassword = user.ResetPassword();
}

HostForLIFE.eu ASP.NET 4.6 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 4.6 Hosting with Milan Data Center - HostForLIFE.eu :: How To Delete Duplicates Elements from List Using IEqualityComparer?

clock October 22, 2015 00:03 by author Peter

In this tutorial, let me show you how to delete duplicates elements from list using IEqualityComparer in ASP.NET 4.6. IEqualityComparer is implemented by classes that need to support an equality comparison for two values of the same type. Generic collections require instances of classes that implement the IEqualityComparer interface in order to provide support for custom data types. IEqualityComparer has two methods to support the comparison of objects for equality. Let us suppose that you have a Employee class that has four properties EmployeeID,FirstName,LastName and Age. Now, you need to write the following code:

public class Employee
{
public Employee()
{
}
public string EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public List&lt;Employee&gt; Employees
{
    get
    {
return new List&lt;Employee&gt;()
        {
new Employee(){EmployeeID="01",FirstName="Peter",LastName="Last01",Age=31},
new Employee(){EmployeeID="02",FirstName="Scott",LastName="Last02",Age=35},
new Employee(){EmployeeID="03",FirstName="Rebecca",LastName="Last03",Age=36},
new Employee(){EmployeeID="01",FirstName="Paul",LastName="Last01",Age=31},
new Employee(){EmployeeID="01",FirstName="Richard",LastName="Last01",Age=31},
        };
    }
}
}

In the above class I have added some dummy records which have duplicates elements. Now,let's remove the duplicate elements from the above class using IEqualityComparer interface.  For this right click on the project and add a new class named EmployeeEquality and inherit this class with IEqualityComparer and write the below code:
public class EmployeeEquality : IEqualityComparer<Employee>
{
public bool Equals(Employee x, Employee y)
{
if (x.EmployeeID == y.EmployeeID && x.FirstName == y.FirstName && x.LastName == y.LastName && x.Age == y.Age)
return true;
return false;
}
public int GetHashCode(Employee obj)
{
//For shake of simplicity
return obj.FirstName.GetHashCode();
}
}


Now,let's display the record on UI. First, right click on the project and add new page,and add the below code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>
</div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<asp:Button ID="btnUnSorted" runat="server" OnClick="btnUnSorted_Click" Text="Duplicates" />
<asp:Button ID="btnWDuplicate" runat="server" OnClick="btnWDuplicate_Click" Text="Without Duplicate" />
</form>
</body>
</html>

In the code behind add following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUnSorted_Click(object sender, EventArgs e)
{
    Employee employee = new Employee();
    GridView1.DataSource = employee.Employees;
    GridView1.DataBind();
}
protected void btnWDuplicate_Click(object sender, EventArgs e)
{
    Employee employee = new Employee();
    List<Employee> list = employee.Employees;
    var distinctEmployee = list.Distinct(new EmployeeEquality());
    GridView1.DataSource = distinctEmployee;
    GridView1.DataBind();
}
}

HostForLIFE.eu ASP.NET 4.6 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 4.6 Hosting Germany - HostForLIFE.eu :: JSON Serialization and Deserialization in ASP.NET 4.6

clock September 14, 2015 06:02 by author Peter

This is all concerning JSON Parsing in ASP.NET. JSON is a info that for running JavaScript on websites. Now a days , JSON is booming on website.This code focuses on JSON serialization and Deserialization in ASP.NET 4.6. First, open your visual studio and then write the following code:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Runtime.Serialization.Json; 
using System.IO; 
using System.Text; 
using System.Text.RegularExpressions; 
/// <summary> 
/// JSON Serialization and Deserialization Class 
/// </summary> 
namespace JsonParsingSample 

public class ClassJsonHelper 

    /// <summary> 
    /// JSON Serialization Method 
    /// </summary> 
    public static string ToJsonConvertor < T > (T t) 
    { 
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); 
        MemoryStream ms = new MemoryStream(); 
        ser.WriteObject(ms, t); 
        string jsonString = Encoding.UTF8.GetString(ms.ToArray()); 
        ms.Close(); 
        //Replace Json Date String 
        string p = @"\\/Date\((\d+)\+\d+\)\\/"; 
        MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString); 
        Regex reg = new Regex(p); 
        jsonString = reg.Replace(jsonString, matchEvaluator); 
        return jsonString; 
    } 
    /// <summary> 
    /// JSON Deserialization Method 
    /// </summary> 
    public static T FromJsonConvertor < T > (string jsonString) 
    { 
        //Convert "yyyy-MM-dd HH:mm:ss" String as "\/Date(1319266795390+0800)\/" 
        string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}"; 
        MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate); 
        Regex reg = new Regex(p); 
        jsonString = reg.Replace(jsonString, matchEvaluator); 
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); 
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); 
        T obj = (T) ser.ReadObject(ms); 
        return obj; 
    } 
    /// <summary> 
    /// Convert Serialization Time /Date(1319266795390+0530) as String 
    /// </summary> 
   private static string ConvertJsonDateToDateString(Match m) 
    { 
      string result = string.Empty; 
        DateTime dt = new DateTime(1970, 1, 1); 
        dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)); 
        dt = dt.ToLocalTime(); 
        result = dt.ToString("yyyy-MM-dd HH:mm:ss"); 
        return result; 
    } 
    /// <summary> 
    /// Convert Date String as Json Time 
    /// </summary> 
    private static string ConvertDateStringToJsonDate(Match m) 
    { 
        string result = string.Empty; 
        DateTime dt = DateTime.Parse(m.Groups[0].Value); 
        dt = dt.ToUniversalTime(); 
        TimeSpan ts = dt - DateTime.Parse("1970-01-01"); 
        result = string.Format("\\/Date({0}+0530)\\/", ts.TotalMilliseconds); 
        return result; 
    } 

HostForLIFE.eu ASP.NET 4.6 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

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in