Sunday, 13 October 2013

How to start your own TV channel using your ASP.NET website

Hello Friend ! Today I will publish new article about How to embed TV channel in your website.

You can do this using Mips.tv


Step-2



You can place html code in your webpage and enjoy your own channel.

Thursday, 10 October 2013

Use of Params Modifier in C#.NET

While victimization the perform member, any numbers of parameter (including none) might seem within the job perform supported want. thus to possess a versatile perform we are able to use params modifier whereas writing the definition of functions.

params keyword specify a way parameter that takes AN argument wherever the numbers of arguments become variable means that parameter arrays enable a variable numbers of arguments to be passed in to a perform. it's additionally sort compatible with the parameters. for instance we are able to send integers , characters, strings at a time to the perform that has the params modifier declared.


private void ParamsUsed()
        {
            ArrayList   listForObject = new ArrayList();
            ArrayList   listForInt = new ArrayList();
            int[] myarray = new int[] { 10, 11, 12 ,13, 14, 15, 16 };
            
            listForObject = UseParams2(100, 200, 'A', "amit");
            listForInt = UseParams(myarray);
            DropDownList1.DataSource = listForObject;
            DropDownList1.DataBind();
            DropDownList2.DataSource = listForInt;
            DropDownList2.DataBind();
        }
public static ArrayList UseParams2(params object[] list)
        {
            ArrayList listT = new ArrayList();
            for (int i = 0; i < list.Length; i++)
            {
                listT.Add(list[i]);
            }
            return listT;
         
        }
public static ArrayList UseParams(params int[] list)
        {
            ArrayList listT = new ArrayList();
            for (int i = 0; i < list.Length; i++)
            {
                listT.Add(list[i]);
            }
            return listT;
        }




How to implement paging in DataList in ASP.NET

While mistreatment the gridView and listView it's a better pratice to use the information electronic device management for pagging purpose.

But whereas you're operating with datalist management then you may face the important drawback, as a result of information|the info|the information}list doesn't support the data electronic device.

In order to impliment the paging functionalty in information list here is that the easiest way.

Take 2 linkbuttons below the information list, named Previous and Next as below.

<asp:LinkButtonID="lbtnPrevious"runat="server"Text= "Previous"OnClick="lbtnPrevious_onClick"></asp:LinkButton>
<asp:LinkButtonID="lbtnNext" runat="server" Text="Next"OnClick="lbtnNext_onClick"></asp:LinkButton>

Now in the code behind declare the
" ViewState["currentPage"] = 0; " in page load event.
Then do as I did in the BindDataList() method.
   ViewState["currentPage"] = 0;
     protected void BindDataList()
         {
             DataTable dt = newDataTable();
             dt = null // assign the datatable with what you want to assign.  
             PagedDataSource page = newPagedDataSource();
             page.AllowPaging = true;
             page.DataSource = dt.DefaultView;
             page.PageSize = 6;
             page.CurrentPageIndex =Convert.ToInt32(ViewState["currentPage"]);
             dlLogoImages.DataSource = page;
             dlLogoImages.DataBind();
             lbtnNext.Enabled = !page.IsLastPage; // Disable the next button if the page is the last page.
             lbtnPrevious.Enabled = !page.IsFirstPage; // Disable the Previuos button if the page is the first page.
         }


 protectedvoid lbtnPrevious_onClick(object sender, EventArgs e)
        {   
            int currentPage = Convert.ToInt32(ViewState["currentPage"]);
            currentPage -= 1; 
            ViewState["currentPage"] = currentPage;
            BindDataList();
        }

   protectedvoid lbtnNext_onClick(object sender, EventArgs e)
       {
            int currentPage = Convert.ToInt32(ViewState["currentPage"]);
            currentPage += 1; 
            ViewState["currentPage"] = currentPage;
            BindDataList();   
      }

Now paging is done in DataList.

    protectedvoid lbtnPrevious_onClick(object sender, EventArgs e)
        {   
            int currentPage = Convert.ToInt32(ViewState["currentPage"]);
            currentPage -= 1; 
            ViewState["currentPage"] = currentPage;
            BindDataList();
        }

   protectedvoid lbtnNext_onClick(object sender, EventArgs e)
       {
            int currentPage = Convert.ToInt32(ViewState["currentPage"]);
            currentPage += 1; 
            ViewState["currentPage"] = currentPage;
            BindDataList();   
      }



I hope this post will be helpful for you

What is use of Yield keyword in C#

Yield may be a keyword that is capable in get list of things from a loop. the function implementing yield keyword returns associate numerable object.Yield retains the state of the tactic throughout the multiple calls. meaning yield returns one component to the business perform and pause the execution of this perform. Next time it'll resume the execution from that time solely and come consequent component. it's a reliable and additional economical thanks to get an inventory of values from a perform. this is often the keyword provided in C#.net 2.0 onward.Yield makes the developer life additional easier. The compiler once compiles the code containing the yield keyword, creates a decent quantity  of IL(Intermediate Language) code. primarily we have a tendency to don't have to be compelled to worry regarding these codes, that's the headache of the compiler.


private void MainProcess()
{
    string[] nameList = GetNames();
    foreach(string name in nameList)
    {
        //do the processing here.
    }
}

private string[] GetNames()
{
    List<string> names = new List<string>();

    for (int i = 0; i < 10; i++)
    {
        names.Add("Name:" + i);
    }

    return names.ToArray();
}

The following code shows the way Yield implements the same thing.

private void MainProcess()
{
    foreach(string name in GetNames())
    {
        //do the processing here.
    }
}

private IEnumerable GetNames()
{
    for (int i = 0; i < 10; i++)
    {
        yield return "Name:" + i;
    }
}



Here, the implementation just in case of Yield is straightforward and undemanding. The GetNames() methodology iterates through the for loop and returns a price every time it's referred to as. The yield come is completely different from the come keyword. wherever the come keyword stops the execution of {the methodology|the tactic|the strategy} and returns the management to the business method, yield come pauses the execution of {the methodology|the tactic|the strategy} and returns the management to the business method. consequent time once we decision the GetNames() methodology the execution resumes from the purpose wherever it left last time.

The yield keyword will take any of the subsequent 2 forms:
- yield come ;
- yield break;

Where yield come  returns the values to the business methodology and paused the execution, yield break ends the execution and for good returns the management to the business perform.

There area unit few restrictions whereas implementing the yield keyword. These are:
- The yield statement will solely seem within associate iterator block.
- Unsafe blocks don't seem to be allowed.
- Parameters to the tactic, operator, or accessor can not be referee or out.
- A yield statement cannot seem in associate anonymous methodology.
- Keep the enumeration code as easy as you'll as a result of debugging it subsequently is sort of not possible.

Initially Yield could feels like bit confusing however once you begin implementing it you'll notice it terribly fascinating and powerful.

How to take Screen Shot grammatically using C# code

You can use this C# code to save lots of the screenshot once there'll be any risk of error within the application .If the consumer is victimization the appliance developer will raise the consumer to send the screenshot in order that he will grasp within which page the error was occured


For Taking picture:
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

   Graphics graphics = Graphics.FromImage(bitmap as Image);

   graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);

   bitmap.Save("c:\\photo.jpeg", ImageFormat.Jpeg);.



  For Send Mail:

        public void SendAttachedEmail(string to, string subject, string path)
        {
            //To connect the SMTP server for mailing.
            try
            {
                MailMessage objMailMsg = new MailMessage(EmailSender, to);
              
                objMailMsg.Subject = subject;
                Attachment objAttachment = new Attachment(path);
                objMailMsg.Attachments.Add(objAttachment);
        System.Net.Mail.SmtpClient objSmtpClient = new SmtpClient("192.168.10.1", 25);
                objSmtpClient.Send(objMailMsg);
            }
            catch (Exception ex)
            {
               throw ex;
            }

        }

C

How to Write dynamicly HTML code using C#

Now I am suggesting for dynamically HTML Code generation  in ASP.Net using C#,

Whenever we have need for creating dynamically menu or any others type controls  we can use this technique.

public static string GetHTML()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<div>");
            sb.Append("<ul>");
            for (int i = 0; i <= 10; i++)
            {
                sb.Append("<li>" + i + " </li>");
            }
            sb.Append("</ul>");
                sb.Append("</div>");

return sb.Tostring();

        }

Here function GetHTML will return a string which has contain HTML code,

You can also this :
<div id="divHTML" runat="server"/>

divHTML.innerHTML=GetHTML();


Basically this concept is very rich for generating report in asp.net because Gridview is heavy wait control then html.

How to Create and Use Stored Procedure in ASP.NET using C# and SQL Server

A hold on procedure could be a cluster of sql statements that has been created and hold on within the info. hold on procedure can settle for input parameters so one procedure is used over the network by many shoppers exploitation completely different computer file. hold on procedure can scale back network traffic and increase the performance. If we tend to modify hold on procedure all the shoppers can get the updated hold on procedure



CREATE PROCEDURE SPR_YourProcedureName
AS
    --Write Your query here
GO
EXEC SPR_YourProcedureName;
GO
DROP PROCEDURE SPR_YourProcedureName;
GO

Advantages of exploitation hold on procedures

a) hold on procedure permits standard programming.

You can produce the procedure once, store it within the info, and decision it any range of times in your program.

b) hold on Procedure permits quicker execution.

If the operation needs an oversized quantity of SQL code is performed repetitively, hold on procedures is quicker. square measure|they're} parsed and optimized after they are initial dead, and a compiled version of the hold on procedure remains in buffer store for later use. this suggests the hold on procedure doesn't ought to be reparsed and reoptimized with every use leading to abundant quicker execution times.

c) hold on Procedure will scale back network traffic.

An operation requiring many lines of Transact-SQL code is performed through one statement that executes the code during a procedure, instead of by causation many lines of code over the network.

d) hold on procedures give higher security to your knowledge

Users is granted permission to execute a hold on procedure notwithstanding they are doing not have permission to execute the procedure's statements directly.

In SQL we tend to area unit having differing types of hold on procedures area unit there

a)    System hold on Proceduresb)    User outlined hold on proceduresc)    Extended hold on Procedures

System hold on Procedures:

System hold on procedures area unit hold on within the master info and these area unit starts with a sp_ prefix. These procedures is accustomed perform form of tasks to support sql server functions for external application calls within the system tables

Ex: sp_helptext [StoredProcedure_Name]

User outlined hold on Procedures:

User outlined hold on procedures area unit sometimes hold on during a user info and area unit usually designed to complete the tasks within the user info. whereas secret writing these procedures don’t use sp_ prefix as a result of if we tend to use the sp_ prefix initial it'll check master info then it involves user outlined info

Extended hold on Procedures:

Extended hold on procedures area unit the procedures that decision functions from DLL files. currently a day’s extended hold on procedures area unit depreciated for that reason it might be higher to avoid exploitation of Extended hold on procedures.

Remove HTML White Space in ASP.NET C#

Hello Friend I am writing here how to remove white space from HTML page

Remove the HTML white space at runtime in ASP.NET will reduce the HTML page size so the page will be load very quickly. This method is for SEO purposes also.

Add the code below to any ASPX.CS page or Master page, then browse the page to see the magic.

using System.Text.RegularExpressions;


        private static readonly Regex REGEX_BETWEEN_TAGS = new Regex(@">\s+<", RegexOptions.Compiled);
        private static readonly Regex REGEX_LINE_BREAKS = new Regex(@"\n\s+", RegexOptions.Compiled);

        protected override void Render(HtmlTextWriter writer)
        {
            using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
            {
                base.Render(htmlwriter);
                string html = htmlwriter.InnerWriter.ToString();

                html = REGEX_BETWEEN_TAGS.Replace(html, "> <");
                html = REGEX_LINE_BREAKS.Replace(html, string.Empty);

                writer.Write(html.Trim());
            }
        }



How to encrypt and decrypt password or any other data in ASP.NET C

In ASP.NET For the security reasons that you wanted to encypt your password or sensitive data before storing it to the database and decypt after getting it from the database using ASP.NET C#.

Here is two simple method on how to encrypt and decrypt your password or data.


EXAMPLE:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center">
<tr>
<td colspan="2">
<b>Encryption and Decryption of Password</b>
</td>
</tr>
<tr>
<td>
UserName
</td>
<td>
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Password
</td>
<td>
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td>
FirstName
</td>
<td>
<asp:TextBox ID="txtfname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
LastName
</td>
<td>
<asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
<div>
<table align="center">
<tr>
<td>
<b>Encryption of Password Details</b>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvUsers" runat="server" CellPadding="4" BackColor="White"
BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px">
<RowStyle BackColor="White" ForeColor="#330099" />
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC"
HorizontalAlign="Left"/>
</asp:GridView>
</td>
</tr>
</table>
</div>
<div>
<table align="center">
<tr>
<td>
<b>Decryption of Password Details</b>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvdecryption" runat="server" BackColor="White"
BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4"
onrowdatabound="gvdecryption_RowDataBound">
<RowStyle BackColor="White" ForeColor="#330099" />
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>



Add System.Text namespace

private const string strconneciton = "Data Source=MYCBJ017550027;Initial Catalog=MySamplesDB;Integrated Security=True";
SqlConnection con = new SqlConnection(strconneciton);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindencryptedData();
BindDecryptedData();
}
}
/// <summary>
/// btnSubmit event is used to insert user details with password encryption
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnSubmit_Click(object sender, EventArgs e)
{
string strpassword = Encryptdata(txtPassword.Text);
con.Open();
SqlCommand cmd = new SqlCommand("insert into SampleUserdetails(UserName,Password,FirstName,LastName) values('" + txtname.Text + "','" + strpassword + "','" + txtfname.Text + "','" + txtlname.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
BindencryptedData();
BindDecryptedData();
}
/// <summary>
/// Bind user Details to gridview
/// </summary>
protected void BindencryptedData()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from SampleUserdetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUsers.DataSource = ds;
gvUsers.DataBind();
con.Close();
}
/// <summary>
/// Bind user Details to gridview
/// </summary>
protected void BindDecryptedData()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from SampleUserdetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvdecryption.DataSource = ds;
gvdecryption.DataBind();
con.Close();
}
/// <summary>
/// Function is used to encrypt the password
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
private string Encryptdata(string password)
{
string strmsg = string.Empty;
byte[] encode = new byte[password.Length];
encode = Encoding.UTF8.GetBytes(password);
strmsg = Convert.ToBase64String(encode);
return strmsg;
}
/// <summary>
/// Function is used to Decrypt the password
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
private string Decryptdata(string encryptpwd)
{
string decryptpwd = string.Empty;
UTF8Encoding encodepwd = new UTF8Encoding();
Decoder Decode = encodepwd.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(encryptpwd);
int charCount = Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
decryptpwd = new String(decoded_char);
return decryptpwd;
}
/// <summary>
/// rowdatabound condition is used to change the encrypted password format to decryption format
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void gvdecryption_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string decryptpassword = e.Row.Cells[2].Text;
e.Row.Cells[2].Text = Decryptdata(decryptpassword);
}
}