How to display video in windows Mediaplayer using C#.net in ASP.NET
Html
Add windows media player using class id and embeded into the gridview control using object id="Player" classid="clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6
<asp:GridView ID="GrdVideo" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<object id="Player" classid="clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6" height="300"
width="300">
<%--<param name="BorderStyle" value="1" />
<param name="MousePointer" value="0" />
<param name="Enabled" value="1" />
<param name="Min" value="0" />
<param name="Max" value="10" />--%>
<param name="url" value='<%#Eval("Video")%>' />
<param name="play" value="0" />
</object>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code
Get values from the database (video Path) and binding into the Gridview control using DataTable .Example for creating Datatable
DataTable myDataTable = new DataTable();
DataColumn myDataColumn;
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "Video";
myDataTable.Columns.Add(myDataColumn);
DataRow row;
row = myDataTable.NewRow();
row["Video"] = strUrl;
myDataTable.Rows.Add(row);
GrdVideo.DataSource = myDataTable.DefaultView;
GrdVideo.DataBind();
How can display VLC ( Video Lan ) Player in ASP.NET
How to display video in windows Mediaplayer using C#.net in ASP.NET
Articles
- Articles(C#.NET) (3)
- ASP.NET (6)
- Asp.Net(Email) (1)
- Asp.net(Image) (2)
- Asp.Net(Web.Config) (2)
- C#.NET (5)
- C#.NET Threading (3)
- C#.NET(ASP.NET) (4)
- Comments in PHP (1)
- Encryption In PHP (1)
- iPhone (Articles) (1)
- JavaScript (1)
- Json with PHP (1)
- LINQ (1)
- PHP (2)
- PHP Constant (1)
- PHP Operators (1)
- PHP Print Command (1)
- PHP Tutorial (2)
- Strings In PHP (1)
- Variable Declaration In PHP (1)
- WPF (1)
- XAML (2)
Blog Archive
About Me
Help Link
Followers
Get All Windows Services and Service Path in ASP.NET using C# .Check If directory and Files existing in the current location. This code also explain how to get values from the xml document.
protected void Button1_Click(object sender, EventArgs e)
{
//Get All Windows Services
RegistryKey services = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services");
if (services != null)
{
//Get Service Path
object pathtoexecutable = services.OpenSubKey("KTSInfoMateServer").GetValue("ImagePath");
string strServicePath = pathtoexecutable.ToString();
int iStartPosition = strServicePath.LastIndexOf('\\');
string strServiceFoldePath = strServicePath.Remove(iStartPosition);
strServiceFoldePath = strServiceFoldePath.Replace('\\', '/');
strServiceFoldePath = strServiceFoldePath.Remove(0, 1);
strServiceFoldePath += "/";
try
{
//Check Direcory Existing
DirectoryInfo objDirectoryInfo = new DirectoryInfo(strServiceFoldePath);
if (objDirectoryInfo.Exists)
{
//Check File Existing in the Service directory
string strSettingsFileName = strServiceFoldePath + "/" + "EmSettings.xml";
FileInfo objFileInfo = new FileInfo(strSettingsFileName);
if (objFileInfo.Exists)
{
XmlNode xNode;
XmlDocument objDoc = new XmlDocument();
objDoc.Load(strSettingsFileName);
string strSettingsXML = objDoc.InnerXml;
XmlNode inXmlNode = objDoc.DocumentElement;
XmlNodeList nodeList;
if (inXmlNode.HasChildNodes)
{
nodeList = inXmlNode.ChildNodes;
for (int iNodeIndex = 0; iNodeIndex <= nodeList.Count - 1; iNodeIndex++)
{
xNode = inXmlNode.ChildNodes[iNodeIndex];
if (xNode != null)
{
if (xNode.Name == "StreamingPort")
{
m_strStreamingPort = xNode.InnerText.ToString();
break;
}
}
}
}
Preview();
lblStatus.Text = "File Exists";
}
else
{
lblStatus.Text = "Not Exists";
}
}
}
catch (Exception objException)
{
string strErrorMessage = objException.Message.ToString();
}
}
}
tag:-
Get All Windows Services and Service Path in ASP.NET using C# .Check If directory and Files existing in the current location. This code also explain how to get values from the xml document.
To change the row color of the GridView control on the onmouseover, onmouseout event.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='Silver'");
// This will be the back ground color of the GridView Control
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='White'");
}
}
tag:-To change the row color of the GridView control on the onmouseover event.
RC4 Encryption in JavaScript
<html>
<head>
<title>RC4 Encryption</title>
</head>
<body>
<script language="JavaScript">
var dg=''
function makeArray(n) {
for (var i=1; i<=n; i ) {
this[i]=0
}
return this
}
function rc4(key, text) {
var i, x, y, t, x2;
status("rc4")
s=makeArray(0);
for (i=0; i<256; i ) {
s[i]=i
}
y=0
for (x=0; x<256; x ) {
y=(key.charCodeAt(x % key.length) s[x] y) % 256
t=s[x]; s[x]=s[y]; s[y]=t
}
x=0; y=0;
var z=""
for (x=0; x<text.length; x ) {
x2=x % 256
y=( s[x2] y) % 256
t=s[x2]; s[x2]=s[y]; s[y]=t
z = String.fromCharCode((text.charCodeAt(x) ^ s[(s[x2] s[y]) % 256]))
}
return z
}
function badd(a,b) { // binary add
var r=''
var c=0
while(a || b) {
c=chop(a) chop(b) c
a=a.slice(0,-1); b=b.slice(0,-1)
if(c & 1) {
r="1" r
} else {
r="0" r
}
c>>=1
}
if(c) {r="1" r}
return r
}
function chop(a) {
if(a.length) {
return parseInt(a.charAt(a.length-1))
} else {
return 0
}
}
function bsub(a,b) { // binary subtract
var r=''
var c=0
while(a) {
c=chop(a)-chop(b)-c
a=a.slice(0,-1); b=b.slice(0,-1)
if(c==0) {
r="0" r
}
if(c == 1) {
r="1" r
c=0
}
if(c == -1) {
r="1" r
c=1
}
if(c==-2) {
r="0" r
c=1
}
}
if(b || c) {return ''}
return bnorm(r)
}
function bnorm(r) { // trim off leading 0s
var i=r.indexOf('1')
if(i == -1) {
return '0'
} else {
return r.substr(i)
}
}
function bmul(a,b) { // binary multiply
var r=''; var p=''
while(a) {
if(chop(a) == '1') {
r=badd(r,b p)
}
a=a.slice(0,-1)
p ='0'
}
return r;
}
function bmod(a,m) { // binary modulo
return bdiv(a,m).mod
}
function bdiv(a,m) { // binary divide & modulo
// this.q = quotient this.mod=remainder
var lm=m.length, al=a.length
var p='',d
this.q=''
for(n=0; n<al; n ) {
p=p a.charAt(n);
if(p.length<lm || (d=bsub(p,m)) == '') {
this.q ='0'
} else {
if(this.q.charAt(0)=='0') {
this.q='1'
} else {
this.q ="1"
}
p=d
}
}
this.mod=bnorm(p)
return this
}
function bmodexp(x,y,m) { // binary modular exponentiation
var r='1'
status("bmodexp " x " " y " " m)
while(y) {
if(chop(y) == 1) {
r=bmod(bmul(r,x),m)
}
y=y.slice(0,y.length-1)
x=bmod(bmul(x,x),m)
}
return bnorm(r)
}
function modexp(x,y,m) { // modular exponentiation
// convert packed bits (text) into strings of 0s and 1s
return b2t(bmodexp(t2b(x),t2b(y),t2b(m)))
}
function i2b(i) { // convert integer to binary
var r=''
while(i) {
if(i & 1) { r="1" r} else {r="0" r}
i>>=1;
}
return r? r:'0'
}
function t2b(s) {
var r=''
if(s=='') {return '0'}
while(s.length) {
var i=s.charCodeAt(0)
s=s.substr(1)
for(n=0; n<8; n ) {
r=((i & 1)? '1':'0') r
i>>=1;
}
}
return bnorm(r)
}
function b2t(b) {
var r=''; var v=0; var m=1
while(b.length) {
v|=chop(b)*m
b=b.slice(0,-1)
m<<=1
if(m==256 || b=='') {
r =String.fromCharCode(v)
v=0; m=1
}
}
return r
}
b64s='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"'
function textToBase64(t) {
status("t 2 b64")
var r=''; var m=0; var a=0; var tl=t.length-1; var c
for(n=0; n<=tl; n ) {
c=t.charCodeAt(n)
r =b64s.charAt((c << m | a) & 63)
a = c >> (6-m)
m =2
if(m==6 || n==tl) {
r =b64s.charAt(a)
if((n%45)==44) {r ="\n"}
m=0
a=0
}
}
return r
}
function base64ToText(t) {
status("b64 2 t")
var r=''; var m=0; var a=0; var c
for(n=0; n<t.length; n ) {
c=b64s.indexOf(t.charAt(n))
if(c >= 0) {
if(m) {
r =String.fromCharCode((c << (8-m))&255 | a)
}
a = c >> m
m =2
if(m==8) { m=0 }
}
}
return r
}
function rand(n) { return Math.floor(Math.random() * n) }
function rstring(s,l) {
var r=""
var sl=s.length
while(l-->0) {
r =s.charAt(rand(sl))
}
//status("rstring " r)
return r
}
function key2(k) {
var l=k.length
var kl=l
var r=''
while(l--) {
r =k.charAt((l*3)%kl)
}
return r
}
function rsaEncrypt(keylen,key,mod,text) {
// I read that rc4 with keys larger than 256 bytes doesn't significantly
// increase the level of rc4 encryption because it's sbuffer is 256 bytes
// makes sense to me, but what do i know...
status("encrypt")
if(text.length >= keylen) {
var sessionkey=rc4(rstring(text,keylen),rstring(text,keylen))
// session key must be less than mod, so mod it
sessionkey=b2t(bmod(t2b(sessionkey),t2b(mod)))
alert("sessionkey=" sessionkey)
// return the rsa encoded key and the encrypted text
// i'm double encrypting because it would seem to me to
// lessen known-plaintext attacks, but what do i know
return modexp(sessionkey,key,mod)
rc4(key2(sessionkey),rc4(sessionkey,text))
} else {
// don't need a session key
return modexp(text,key,mod)
}
}
function rsaDecrypt(keylen,key,mod,text) {
status("decrypt")
if(text.length <= keylen) {
return modexp(text,key,mod)
} else {
// sessionkey is first keylen bytes
var sessionkey=text.substr(0,keylen)
text=text.substr(keylen)
// un-rsa the session key
sessionkey=modexp(sessionkey,key,mod)
alert("sessionkey=" sessionkey)
// double decrypt the text
return rc4(sessionkey,rc4(key2(sessionkey,text),text))
}
}
function trim2(d) { return d.substr(0,d.lastIndexOf('1') 1) }
function bgcd(u,v) { // return greatest common divisor
// algorythm from http://algo.inria.fr/banderier/Seminar/Vallee/index.html
var d, t
while(1) {
d=bsub(v,u)
//alert(v " - " u " = " d)
if(d=='0') {return u}
if(d) {
if(d.substr(-1)=='0') {
v=d.substr(0,d.lastIndexOf('1') 1) // v=(v-u)/2^val2(v-u)
} else v=d
} else {
t=v; v=u; u=t // swap u and v
}
}
}
function isPrime(p) {
var n,p1,p12,t
p1=bsub(p,'1')
t=p1.length-p1.lastIndexOf('1')
p12=trim2(p1)
for(n=0; n<2; n =mrtest(p,p1,p12,t)) {
if(n<0) return 0
}
return 1
}
function mrtest(p,p1,p12,t) {
// Miller-Rabin test from forum.swathmore.edu/dr.math/
var n,a,u
a='1' rstring('01',Math.floor(p.length/2)) // random a
//alert("mrtest " p ", " p1 ", " a "-" p12)
u=bmodexp(a,p12,p)
if(u=='1') {return 1}
for(n=0;n<t;n ) {
u=bmod(bmul(u,u),p)
//dg =u " "
if(u=='1') return -100
if(u==p1) return 1
}
return -100
}
pfactors='11100011001110101111000110001101'
// this number is 3*5*7*11*13*17*19*23*29*31*37
function prime(bits) {
// return a prime number of bits length
var p='1' rstring('001',bits-2) '1'
while( ! isPrime(p)) {
p=badd(p,'10'); // add 2
}
alert("p is " p)
return p
}
function genkey(bits) {
q=prime(bits)
do {
p=q
q=prime(bits)
} while(bgcd(p,q)!='1')
p1q1=bmul(bsub(p,'1'),bsub(q,'1'))
// now we need a d, e, and an n so that:
// p1q1*n-1=de -> bmod(bsub(bmul(d,e),'1'),p1q1)='0'
// or more specifically an n so that d & p1q1 are rel prime and factor e
n='1' rstring('001',Math.floor(bits/3) 2)
alert('n is ' n)
factorMe=badd(bmul(p1q1,n),'1')
alert('factor is ' factorMe)
//e=bgcd(factorMe,p1q1)
//alert('bgcd=' e)
e='1'
// is this always 1?
//r=bdiv(factorMe,e)
//alert('r=' r.q " " r.mod)
//if(r.mod != '0') {alert('Mod Error!')}
//factorMe=r.q
d=bgcd(factorMe,'11100011001110101111000110001101')
alert('d=' d)
if(d == '1' && e == '1') {alert('Factoring failed ' factorMe ' p=' p ' q=' q)}
e=bmul(e,d)
r=bdiv(factorMe,d)
d=r.q
if(r.mod != '0') {alert('Mod Error 2!')}
this.mod=b2t(bmul(p,q))
this.pub=b2t(e)
this.priv=b2t(d)
}
function status(a) { }//alert(a)}
</script>
<script language="JavaScript">
<!--
function rc4encrypt() {
document.rc4.text.value=textToBase64(rc4(document.rc4.key.value,document.rc4.text.value))
}
function rc4decrypt() {
document.rc4.text.value=(rc4(document.rc4.key.value,base64ToText(document.rc4.text.value)))
}
-->
</script>
<h3>RC4 Encryption (input text for both field):</h3>
<form method="POST" name="rc4">
<div align="center">
<table border="0">
<tr>
<td align="right">
Key:
</td>
<td>
<input type="text" size="60" name="key" value="">
</td>
</tr>
<tr>
<td align="right">
Text:
</td>
<td>
<textarea name="text" rows="6" cols="70"></textarea>
</td>
</tr>
<tr>
<td>
<p align="center">
<input type="button" name="B1" value="Encrypt" onclick="rc4encrypt()">
<input type="button" name="B2" value="Decrypt" onclick="rc4decrypt()">
</p>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
To compute the GridView Sum in asp.net let’s take a simple example of SQL Database table. For GridView sum in ASP.net you can use the Northwind SQL database table to test the source code given in this tutorial. Here we will use products SQL table of Northwind database. In this tutorial we will compute the sum of units in stock of each product in the specified category.
Now you are ready to connect this SQL table with ASP.net web page to display the records in SQL table. But still you need a control to display the records in tabular format so that you could show the sum of column exactly below the Units in Stock column of GridView control.
HTML code with Auto Formatted GridView in ASP.Net Web Page
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="2" ShowFooter="true">
<Columns>
<asp:TemplateField HeaderText="Product Name" HeaderStyle-Width="200px">
<ItemTemplate> <%# DataBinder.Eval(Container.DataItem, "ProductName") %>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="Label1" runat="server" Text="Total Units">
</asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Units In Stock">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "UnitsInStock") %></ItemTemplate>
<FooterTemplate><asp:Label ID="Label2" runat="server"></asp:Label></FooterTemplate></asp:TemplateField></Columns><HeaderStyle HorizontalAlign="Left" /><FooterStyle BackColor="#cccccc" Font-Bold="true" /></asp:GridView>
In the above HTML code of GridView control of ASP.Net 2.0 you can notice that we have created two columns of GridView using ItemTemplate of TemplateField to display the Product Name and Units in stock Columns of Products Table. In both TemplateField columns we also added FooterTemplate sections having Label controls. Under product name column Text property of Label control has been set to "Total Unit". For the Label control placed inside the FooterTemplate of second TemplateField displaying the Units In Stock column we will set its Text property dynamically after computing the sum of associated column.
C# Sample code to Compute the Sum of Column in GridView control of ASP.Net
SqlCommand mySqlCommand = new SqlCommand("select productid, productname, unitsinstock from products where categoryid = @categoryid", mySQLconnection);
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlCommand);
mySqlCommand.Parameters.Add("@categoryid", SqlDbType.Int).Value = 1;
DataSet myDataSet = new DataSet();
mySqlAdapter.Fill(myDataSet);
GridView1.DataSource = myDataSet;GridView1.DataBind();((Label)GridView1.FooterRow.Cells[1].FindControl("Label2")).Text = myDataSet.Tables[0].Compute("sum(unitsinstock)", "").ToString();
In the above C# code Compute function is used that returns the passed expression for all the rows of a table in a dataset. According to above code, it will return the sum of units in stock for each product in the specified category.
Compute function of DataTable in ASP.Net
Compute function takes 2 parameters:
1.String Expression:
Expression as a agregate function of sql.
2.String Filter:
Filter criteria to filter the retrived rows.
E.g.:
((Label)GridView1.FooterRow.Cells[1].FindControl("Label2")).Text = myDataSet.Tables[0].Compute("sum(unitsinstock)", "categoryid=1").ToString();
Above C# example code line shows that you can also specify the string Filter as a second parameter of Compute function to evaluate the result according to to specified string expression as aggregate function as a first parameter.
tag:-ASP.Net 2.0 GridView Compute Column Sum using C#
This tutorial will show you how to display data using the .NET GridView Control, stored procedures, ASP.NET 2.0 and C#.NET
Querying an SQL database with stored procedures using C# .NET is easy to do.
First, you will need to import the System.Data.SqlClient namespace.
The System.Data.SqlClient namespace contains the SqlCommand and SqlConnection classes that we need in order to connect to our database and to send an SQL command to it.
using System.Data.SqlClient;
We'll put our code in the Page_Load() event.
When the Page_Load() event fires, a new SqlCommand object is instantiated with our connection string and our stored procedure name. We add the parameters needed for the stored procedure by using our SqlCommand object's Parameters.Add() method.
Afterwards, we will attempt to connect using the Open() method of our cmd.Connection object. Once it is connected we will attempt to execute the stored procedure we specified earlier (in this example CustOrderHist stored procedure in the Northwind db).
If all goes well, we will have the results of our SQL query assigned to the gvwExample's DataSource property. Now all we have to do is call the DataBind() method of our gvwExample to bind the data to the control. The data is now ready to be displayed.
protected void Page_Load(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand("CustOrderHist", new SqlConnection("Server=localhost;Database=Northwind;Trusted_Connection=True;"));
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("CustomerID", txtCustID.Text);
cmd.Connection.Open();
gvwExample.DataSource = cmd.ExecuteReader();
gvwExample.DataBind();
cmd.Connection.Close();
cmd.Connection.Dispose();
}
catch (Exception ex)
{
lblStatus.Text = ex.Message;
}
}
We have to add a few tags on the front end of the .aspx page to place where we want the GridView control to display its bound data. We also specify what part of the data from the data set we would like to display. The front end .aspx page looks something like this:
<table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#cccccc">
<tr>
<td width="100" align="right" bgcolor="#eeeeee" class="header1"> Customer Data Using Stored Procedures:</td>
<td align="center" bgcolor="#FFFFFF">
<asp:GridView ID="gvwExample" runat="server" AutoGenerateColumns="False" CssClass="basix" >
<columns>
<asp:BoundField DataField="ProductName" HeaderText="Product Name" />
<asp:BoundField DataField="Total" HeaderText="Total" />
</columns>
</asp:GridView>
<br />
Customer ID:
<asp:TextBox ID="txtCustID" runat="server" Width="42px">ALFKI</asp:TextBox>
Order ID:<asp:TextBox ID="txtOrderID" runat="server" Width="43px">10256</asp:TextBox><br />
<asp:Button ID="btnSubmit" runat="server" Text="Go" />
<br />
<asp:label ID="lblStatus" runat="server"></asp:label></td>
</tr>
</table>
The flow for the code behind page is as follows.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand("CustOrderHist", new SqlConnection("Server=localhost;Database=Northwind;Trusted_Connection=True;"));
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("CustomerID", txtCustID.Text);
cmd.Connection.Open();
gvwExample.DataSource = cmd.ExecuteReader();
gvwExample.DataBind();
cmd.Connection.Close();
cmd.Connection.Dispose();
}
catch (Exception ex)
{
lblStatus.Text = ex.Message;
}
}
}
tag:- Using Stored Procs with ASP.NET 2.0 GridView and C#
Related Articles
Find Checkbox control in the Gridview and Check box is checked or not
Get Cell Contents in GridView using C#.Net
How To Find HeaderRow in GridView Using C#.Net in Asp.net
How to populate Treeview Control in Asp.Net using C# . Add Treeview Control from the toolbox .
Id : TreeView1
Sample application for Treeview Control
protected void Button1_Click(object sender, EventArgs e)
{
TreeNode tNode = new TreeNode();
tNode.Text = "Sreejith";
TreeView1.Nodes.Add(tNode);
TreeView1.Nodes[0].Checked = true;
for (int i = 0; i < 5; i++)
{
TreeNode tNode1 = new TreeNode();
tNode1.Text = i.ToString();
TreeView1.Nodes[0].ChildNodes.Add(tNode1);
if (i % 2 == 0)
{
TreeView1.Nodes[0].ChildNodes[i].Checked = true;
}
for (int j = 0; j < 2; j++)
{
TreeNode tNode2 = new TreeNode();
tNode2.Text = j.ToString();
TreeView1.Nodes[0].ChildNodes[i].ChildNodes.Add(tNode2);
}
}
}
tage:- How to populate Treeview Control in Asp.Net using C# . Add Treeview Control from the toolbox
Find Checkbox control in each row of the Gridview and Check box is checked or not and also select and deselect all checkbox in the Gridview .Implement Findcontrol method in the Gridview ..
/// Find check box control in the Gridview and Check box is checked or not
protected void btnList_Click(object sender, EventArgs e)
{
//Get number of rows in the GridView
int iCount = this.grdCourse.Rows.Count;
this.lstCourseId.Items.Clear();
for (int iIndex = 0; iIndex < iCount; iIndex++)
{
//Find Checkbox control in each row of the gridview..
CheckBox chkCourceId = ((CheckBox)this.grdCourse.Rows[iIndex].FindControl("chkId"));
//If checkbox is checked
if (chkCourceId.Checked)
{
//Get Course Id in each row of the gridview..
string strCourceId = this.grdCourse.Rows[iIndex].Cells[1].Text.ToString();
//Add CourseId Value into the Listbox Control
this.lstCourseId.Items.Add(strCourceId);
}
}
}
// Select and deselect all checkboxes in te Griview Control
protected void chkSelectAll_CheckedChanged(object sender, EventArgs e)
{
//Get number of rows in the GridView
int iCount = this.grdCourse.Rows.Count;
//If Select All check Box is checked
if (this.chkSelectAll.Checked)
{
for (int iIndex = 0; iIndex < iCount; iIndex++)
{
//Find Checkbox control in each row of the gridview..
CheckBox chkCourceId = ((CheckBox)this.grdCourse.Rows[iIndex].FindControl("chkId"));
// If checkbox is not checked
if (!chkCourceId.Checked)
{
chkCourceId.Checked = true;
}
}
}
else
{
for (int iIndex = 0; iIndex < iCount; iIndex++)
{
//Find Checkbox control in each row of the gridview..
CheckBox chkCourceId = ((CheckBox)this.grdCourse.Rows[iIndex].FindControl("chkId"));
// If checkbox is checked in the gridview
if (chkCourceId.Checked)
{
chkCourceId.Checked = false;
}
}
}
}
Please aply these code into the design (html) page...
<asp:GridView ID="grdCourse" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkID" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnList" runat="server" OnClick="btnList_Click" Text="List" />
<asp:CheckBox ID="chkSelectAll" runat="server" AutoPostBack="True"
OnCheckedChanged="chkSelectAll_CheckedChanged" Text="Select All" />
tag:-
Dowload a YouTube Video Usong C#.Net .How can download YouTube Video using C#.net in windows application
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Net;
using System.Reflection;
using System.IO;
using System.Runtime.InteropServices;
namespace DownloadYouTube
{
public partial class Form1 : Form
{
string current_working_directory = Application.StartupPath; // This is used to determine where to save the video.
string youtube_video_title = "video"; // This gets set near the end of get_download_url()
string strUrl = @"http://www.youtube.com/watch?v=_QUrWjEGj34&feature=fvhl";///* insert video URL here*/
public Form1()
{
InitializeComponent();
}
private void btnDownload_Click(object sender, EventArgs e)
{
string youtube_url = makeYouTubeURLCompliant(strUrl); // This makes the URL compliant with the code.
string download_url = get_download_url(youtube_url); // This extracts the download URL from the YouTube website HTMl source code.
download_video_from_url(download_url); // This actually downloads the video. I haven't tested this as I used someone elses queue download class for my own downloading needs.
}
public string get_download_url(string url)
{
string download_url = null;
string buffer = getYouTubePageContent(url);
string title = string.Empty;
if (buffer.IndexOf("Error:") < 0)
{
int start = 0, end = 0;
string startTag = "/watch_fullscreen?";
string endTag = ";";
start = buffer.IndexOf(startTag, StringComparison.CurrentCultureIgnoreCase);
end = buffer.IndexOf(endTag, start, StringComparison.CurrentCultureIgnoreCase);
string str = buffer.Substring(start + startTag.Length, end - (start + startTag.Length));
string vid = str.Substring(str.IndexOf("video_id"), str.IndexOf("&", str.IndexOf("video_id")) - str.IndexOf("video_id"));
string l = str.Substring(str.IndexOf("&l"), str.IndexOf("&", str.IndexOf("&l") + 1) - str.IndexOf("&l"));
string t = str.Substring(str.IndexOf("&t"), str.IndexOf("&", str.IndexOf("&t") + 1) - str.IndexOf("&t"));
title = str.Substring(str.IndexOf("&title=") + 7);
download_url = "http://youtube.com/get_video?" + vid + l + t;
}
else
{
MessageBox.Show("Error downloading video");
}
youtube_video_title = title;
return download_url;
}
private string makeYouTubeURLCompliant(string url)
{
url = url.Replace("www.youtube.com", "youtube.com");
if (url.IndexOf("http://youtube.com/v/") >= 0)
{
url.Replace("http://youtube.com/v/", "http://youtube.com/watch?v=");
}
if (url.IndexOf("http://youtube.com/watch?v=") < 0)
{
url = "";
}
return (url);
}
// This is a helper method is used by get_download_url()
private string getYouTubePageContent(string url)
{
string buffer;
try
{
string outputBuffer = "where=46038";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentLength = outputBuffer.Length;
req.ContentType = "application/x-www-form-urlencoded";
StreamWriter swOut = new StreamWriter(req.GetRequestStream());
swOut.Write(outputBuffer);
swOut.Close();
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
buffer = sr.ReadToEnd();
sr.Close();
}
catch (Exception exp)
{
buffer = "Error: " + exp.Message.ToString();
}
return (buffer);
}
private void download_video_from_url(string url)
{
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri(url), @current_working_directory + "\\" + makeTitleFileCompliant(youtube_video_title) + ".flv");
}
// This method makes the YouTube title compliant as a filename
public string makeTitleFileCompliant(string title_uncomp)
{
return title_uncomp.Replace("\\", "").Replace("/", "").Replace("*", "").Replace(":", "").Replace("?", "").Replace("\"", "").Replace("<", "").Replace(">", "").Replace("|", "");
}
}
}
Get a Cell value in Gridview using C#.net .Implement these code into the Gridview's DataBound Event .Find Header Row in the Gridview and to replace some value into the Cell corresponding Header Row.
#region Set Female and Male Value into the Personal Gridview
protected void grdPersonalDetails_DataBound(object sender, EventArgs e)
{
GridViewRow headerRow = grdPersonalDetails.HeaderRow;
for (int iIndex = 0; iIndex < headerRow.Cells.Count; iIndex++)
{
//Get Header Name
string strHeaderName = headerRow.Cells[iIndex].Text.ToString();
if (strHeaderName == "Gender")
{
for (int iValue = 0; iValue < grdPersonalDetails.Rows.Count; iValue++)
{
//Get Cell value
string strGender = grdPersonalDetails.Rows[iValue].Cells[iIndex].Text; //Check Male
if (strGender == "1")
{
grdPersonalDetails.Rows[iValue].Cells[iIndex].Text = "Male";
}
//check Female
if (strGender == "2")
{
grdPersonalDetails.Rows[iValue].Cells[iIndex].Text = "Female";
}
}
break;
}
}
#endregion
tag:-Get a Cell value in Gridview using C#.net .Implement these code into the Gridview's DataBound Event .Find Header Row in the Gridview and to replace some value into the Cell corresponding Header Row.
Find Header Row in Gridview using C#.net .Implement these code into the Gridview's DataBound Event .Find Header Row in the Gridview and to replace some value into the Cell corresponding Header Row.
#region Set Female and Male Value into the Personal Gridview
protected void grdPersonalDetails_DataBound(object sender, EventArgs e)
{
GridViewRow headerRow = grdPersonalDetails.HeaderRow;
for (int iIndex = 0; iIndex < headerRow.Cells.Count; iIndex++)
{
//Get Header Name
string strHeaderName = headerRow.Cells[iIndex].Text.ToString();
if (strHeaderName == "Gender")
{
for (int iValue = 0; iValue <>string strGender = grdPersonalDetails.Rows[iValue].Cells[iIndex].Text; //Check Male
if (strGender == "1")
{
grdPersonalDetails.Rows[iValue].Cells[iIndex].Text = "Male";
}
//check Female
if (strGender == "2")
{
grdPersonalDetails.Rows[iValue].Cells[iIndex].Text = "Female";
}
}
break;
}
}
#endregion
tag:-Find Header Row in Gridview using C#.net .Implement these code into the Gridview's DataBound Event .Find Header Row in the Gridview and to replace some value into the Cell corresponding Header Row.
We can edit,delete,add keys and values into Ap.config using C#.NET ?
First off all using system.configuration.dll (if not exist) then using namespace System.Configuration
Then add app.config file
that file contain only appSettings tag
Call this Function "SaveConfigValue"
SaveConfigValue(strkeyDatabaseType, strType);
SaveConfigValue(strkeyServer, strServer);
SaveConfigValue(strkeyUsername, strUserName);
SaveConfigValue(strkeyPassword, strPass);
SaveConfigValue(strkeyDatabase, strDatabase);
#region Save Database Settings into Config File
///
/// Save Database Settings into Config File
///
///
///
///
private bool SaveConfigValue(string strKey, string strValue)
{
bool bRet = true;
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove(strKey);
config.AppSettings.Settings.Add(strKey, strValue);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
bRet = false;
}
return bRet;
}
#endregion
#region Load DataBaseSettings
///
/// Load Database settings from Config File
///
///
private bool LoadConfigValue()
{
bool bRet = true;
try
{
ConfigurationManager.RefreshSection("appSettings");
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
foreach (string strKey in config.AppSettings.Settings.AllKeys)
{
string strVal = ConfigurationManager.AppSettings[strKey].ToString();
switch(strKey)
{
case strkeyDatabaseType:
{
if (strVal == strDatabaseTypeAccess)
{
radioButtonAccess.Checked = true;
}
else
{
radioButtonSqlServer.Checked = true;
}
break;
}
case strkeyServer:
txtServer.Text = strVal;
break;
case strkeyUsername:
txtUserName.Text = strVal;
break;
case strkeyPassword:
txtPassword.Text = strVal;
break;
case strkeyDatabase:
txtConnectionString.Text = strVal;
break;
}
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
bRet = false;
}
return bRet;
}
#endregion
#tag:-Add,Delete,Edit App.config File Using C#.Net
// Executing external applications in C#.Net (using process)
/*
Before we begin creating any methods, we must include System.Diagnostics namespace(using System.Diagnostics), witch contains the Process class.
Also, we must declare a private variable of type Process in our class.
Let's name the variable p.
*/
/// Start Your Process
private void btnStart_Click(object sender, EventArgs e)
{
Process p = new Process();
p.StartInfo.FileName = txtProcessName.Text.Trim();
p.Start();
}
/// Browse your Executable Programs
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog dlgOpenFileDialog = new OpenFileDialog();
if (dlgOpenFileDialog.ShowDialog() == DialogResult.OK)
{
txtProcessName.Text = dlgOpenFileDialog.FileName;
}
}
//In this case you can type any executable commands into the textbox (cmd,notepad,mspaint ..etc) or browse
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language . JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
JSON is built on two structures:
* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
* An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangable with programming languages also be based on these structures.
In JSON, they take on these forms:
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
A string is a collection of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.
A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.
Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, that completely describes the language.
Example :
object
{}
{ members }
members
pair
pair , members
pair
string : value
array
[]
[ elements ]
elements
value
value , elements
value
string
number
object
array
true
false
null
-----------------
string
""
" chars "
chars
char
char chars
char
any-Unicode-character-
except-"-or-\-or-
control-character
\"
\\
\/
\b
\f
\n
\r
\t
\u four-hex-digits
number
int
int frac
int exp
int frac exp
int
digit
digit1-9 digits
- digit
- digit1-9 digits
frac
. digits
exp
e digits
digits
digit
digit digits
e
e
e+
e-
E
E+
E-
tag:-JSON with PHP Introduction
The crypt() Function
In PHP we can use the crypt () function to create one way encryption. This means that the data is encrypted but cannot easily be decrypted.
When a user chooses their password, the password is then encrypted and the encrypted version of this password is saved. The next time the user goes to login, their password is encrypted again and then checked against the already saved (encrypted) version to see if they are the same. This way if the data is intercepted, they only ever see the encrypted version.
The crypt function is phrased as: crypt ( input_string, salt)
In this case input_string is the string you would like to encrypt (your password for example,) and salt is an optional parameter that influences how the encryption will work. PHP by default uses a two character DES salt string. If your system standard is MD5, a 12-character salt string is used.
The following are the four types of salt that work with all crypt () functions.
CRYPT_STD_DES - Standard DES-based encryption with a two character salt
CRYPT_EXT_DES - Extended DES-based encryption with a nine character salt
CRYPT_MD5 - MD5 encryption with a twelve character salt starting with $1$
CRYPT_BLOWFISH - Blowfish encryption with a sixteen character salt starting with $2$ or $2a$
when we use crypt ()
<?php $password = crypt('mypassword'); print $password . %u201C is the encrypted version of mypassword%u201D; ?>
This will output the encrypted version of ‘mypassword’ for you to see. Now let’s try it using different types of salt.
<?
php $password = crypt('mypassword' , 'd4');
print $password . " is the CRYPT_STD_DES version of mypassword<br>";
$password = crypt('mypassword' , 'k783d.y1g');
print $password . " is the CRYPT_EXT_DES version of mypassword<br>";
$password = crypt('mypassword' , '$1$d4juhy6d$');
print $password . " is the CRYPT_MD5 version of mypassword<br>";
$password = crypt('mypassword' , '$2a$07$kiuhgfslerd...........$');
print $password . " is the CRYPT_BLOWFISH version of mypassword<br>";
?>
This will output something like this:
d4/qPbCcJ5tD. is the CRYPT_STD_DES version of mypassword
k7xEagYCDPPSc is the CRYPT_EXT_DES version of mypassword
$1$d4juhy6d$a.jIPYnvne1FWF2V6mGQR0 is the CRYPT_MD5 version of mypassword
$2a$07$kiuhgfslerd...........6k0kSI76CqJ/RWGnSp9MWRDF91gJZfW is the CRYPT_BLOWFISH version of mypassword
tag:- crypt() funtion for data encryption in PHP
How can Read/Write in App.Config File using C#.Net
1.Create app.config File
<add key="EMConnectionstring" value="Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source = D:EventManagementSystem.mdb" />
2. Add new reference "System.Configure" dll
using System.Configuration;
// Open App.Config of executable
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//ConfigurationSettings.AppSettings.
string value = string.Empty;
foreach (string key in ConfigurationManager.AppSettings)
{
value = ConfigurationManager.AppSettings[key].ToString();
}
config.AppSettings.Settings.Add("EMConnectionstring", value);
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
Different types of Operators using in PHP they are Arithemtic Operators,Assignment Operators,Comparison Operators,Increment/decrement Operators,Logic Operators,String Operators
Arthimetic Operators
Example Name Result
-$a Negation Opposite of $a.
$a - $b Subtraction Difference of $a and $b.
$a + $b Addition Sum of $a and $b.
$a / $b Division Quotient of $a and $b.
$a % $b Modulus Remainder of $a divided by $b.
$a * $b Multiplication Product of $a and $b.
Assignment Operators
The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the rights (that is, "gets set to").
Example :
<?php
$a = ($b = 4) 5; // $a is equal to 9 now, and $b has
been set to 4.
?>
Comparison Operators
PHP using Comparison operators in C,C++,java except "===" operator
Example Name Result
$a == $b Equal TRUE if $a is equal to $b.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type.
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type.
$a < $b Less than TRUE if $a is strictly less than $b. $a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.
Increment and Decrement Operator
++,-- operators
Example Name Effect
++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one
--$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.
Example:
<?phpecho "<h3>Postincrement</h3>";
$a = 5;
echo "Should be 5: " . $a . "<br />\n";echo "Should be 6: " . $a . "<br />\n";
echo "<h3>Preincrement</h3>";
$a = 5;
echo "Should be 6: " . $a . "<br />\n";echo "Should be 6: " . $a . "<br />\n";
echo "<h3>Postdecrement</h3>";
$a = 5;
echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
echo "<h3>Predecrement</h3>";
$a = 5;
echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
?>
Arithemetic Operator on Character Variable
Example :
<?php
$i = 'W';
for ($n=0; $n<6; $n )
{
echo $i . "\n";
}
?>
The above example will output:
X Y Z AA AB AC
String Operators
There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side.
Example :
<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"
?>
Logical Operators
Example Name Result
$a and $b And TRUE if both $a and $b are TRUE.
$a or $b Or TRUE if either $a or $b is TRUE.
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.
! $a Not TRUE if $a is not TRUE.
$a || $b Or TRUE if either $a or $b is TRUE
$a && $b And TRUE if both $a and $b are TRUE.
tag:-PHP Operators,Arithmetic Operators,Relational Operators,Increment and Decremet,String Operators,Logical Operatos
Constants in PHP : using define()-function
Constant
A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script . A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.
How can declare Constant ?
You can define a constant by using the define()-function. Once a constant is defined, it can never be changed or undefined.
<?php// Valid constant namesdefine("FOO", "something");define("FOO2", "something else");define("FOO_BAR", "something more");// Invalid constant namesdefine("2FOO", "something");
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."?>
Important things ..
- Constants do not have a dollar sign ($) before them;
- Constants may only be defined using the define() function.
- Constants may only evaluate to scalar values (integer,float,boolean,strings).
tag:-Contants definition,How can declare constant in PHP ?,Constant Syntax in PHP
iText for C#.net
Creation of PDF Document in 5 easy steps
Step 1: First create an instance of document object
Document myDocument= new Document(PageSize.A4.Rotate());
Step 2: Now create a writer that listens to this doucment and writes the document to desired Stream.
PdfWriter.GetInstance(myDocument, new FileStream("Salman.pdf", FileMode.Create));
Step 3: Open the document now using
myDocument.Open();
Step 4: Now add some contents to the document
myDocument.add( new Paragraph ( "First Pdf File made by Salman using iText"));
Step 5: Remember to close the documnet
myDocument.close();
// Code
using System;
using System.IO;
using System.Diagnostics;
using iTextSharp.text;
using iTextSharp.text.pdf;
public class iTextDemo
{
public static void Main()
{
Console.WriteLine("iText Demo");
// step 1: creation of a document-object
Document myDocument = new Document(PageSize.A4.Rotate());
try
{
// step 2:
// Now create a writer that listens to this doucment and writes the document to desired Stream.
PdfWriter.GetInstance(myDocument, new FileStream("Salman.pdf", FileMode.Create));
// step 3: Open the document now using
myDocument.Open();
// step 4: Now add some contents to the document
myDocument.Add(new Paragraph("First Pdf File made by Salman using iText"));
}
catch(DocumentException de)
{
Console.Error.WriteLine(de.Message);
}
catch(IOException ioe)
{
Console.Error.WriteLine(ioe.Message);
}
// step 5: Remember to close the documnet
myDocument.Close();
}
}
tag:- Create PDF Files on fly in C#
If you've got a Stream in .NET - whether its fetched from a HttpWebRequest or read from another file - you can easily save this stream to another file using the following code.
// readStream is the stream you need to read
// writeStream is the stream you want to write to
private void ReadWriteStream(Stream readStream, Stream writeStream)
{
int Length = 256;
Byte [] buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer,0,Length);
// write the required bytes
while( bytesRead > 0 )
{
writeStream.Write(buffer,0,bytesRead);
bytesRead = readStream.Read(buffer,0,Length);
}
readStream.Close();
writeStream.Close();
}
To call this method, just do something like this:
string saveTo = "some path to save"
// create a write stream
FileStream writeStream = new FileStream(saveTo, FileMode.Create, FileAccess.Write);
// write to the stream
ReadWriteStream(readStream,writeStream);
How to upload file from the local machine to webserver,and download its from the server to local machine .
1.Fileupload.aspx : for uploading files
Need two textbox controls
a.Uploading Folder FilePath(Enter the url of the website: Eg:
http://someserver/someapplication/receiver.aspx)
b.Enter the location of the local file location: Eg: c:\somefile.doc
2.FileDownload.aspx :downloading files
3.Reciever.aspx
using System.Net;
using System.IO;
using System.Text;
Fileupload.aspx
protected void cmdSend_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
try
{
WebClient oclient = new WebClient();
byte[] responseArray = oclient.UploadFile(txtURLToSend.Text, "POST",
txtFileToSend.Text);
lblStatus.Text = "Check the file at " + Encoding.ASCII.GetString(responseArray);
}
catch (Exception ex)
{
lblStatus.Text = ex.Message;
}
}
FileDownload.aspx
using System.Net;
using System.IO;
using System.Text;
protected void cmdSend_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
try
{
WebClient oclient = new WebClient();
byte[] responseArray = oclient.UploadFile(txtURLToSend.Text, "POST",
txtFileToSend.Text);
lblStatus.Text = "Check the file at " + Encoding.ASCII.GetString(responseArray);
}
catch (Exception ex)
{
lblStatus.Text = ex.Message;
}
}
create "ReceivedFiles" Folder in the Current Directory and create reciever.aspx file
Reciever.aspx
protected void Page_Load(object sender, System.EventArgs e)
{
foreach(string f in Request.Files.AllKeys)
{
HttpPostedFile file = Request.Files[f];
file.SaveAs(Server.MapPath("ReceivedFiles") + "\\" +
file.FileName);
}
}
tag:-How to upload file from the local machine to webserver,and download its from the server to local machine in ASP.NET using C#.NET
Media Player in Internet Explorer and Mozilla FireFox
IE has interesting dynsrc parameter for the tag. The code can look like this:
<img dynsrc="MyVideo.avi" />
More compatible solution is to use <embed> tag. This solution is better since it is supported by different web browsers (notice that it is not recommended by W3C as standard HTML). Code can look like this:
<embed src="MyVideo.avi"></embed>
Instead of using of <embed> tag, W3C recommends <object> tag. Here is the code to display WMV video file with <object> HTML tag:
<object height="320px" width="240px" type ="video/x-ms-wmv">
<param name="src" value="http://localhost/MyMovie.wmv" />
</object>
Display video with Media Player active X control in Internet Explorer
More flexible way to show video on your ASP.NET web site is to use Windows Media Player active X control. Media player is probalbly already used by most of your site visitors. So they feel familiar with it. Also, Media Player supports many different file types. This control in Internet Explorer web browser is presented with <object> HTML tag with code like this:
<OBJECT width="312px" height="248px" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" VIEWASTEXT>
<PARAM name="autoStart" value="False">
<PARAM name="URL" value="./Movie/Pljacka.wmv">
<PARAM name="enabled" value="True">
<PARAM name="balance" value="0">
<PARAM name="currentPosition" value="0">
<PARAM name="enableContextMenu" value="True">
<PARAM name="fullScreen" value="False">
<PARAM name="mute" value="False">
<PARAM name="playCount" value="1">
<PARAM name="rate" value="1">
<PARAM name="stretchToFit" value="False">
<PARAM name="uiMode" value="full">
</OBJECT>
Display Media Player control in Mozilla FireFox
Firefox uses <object> or <embed> tags to show Media Player control. Before you try this, Firefox needs the Windows Media Player browser plugin installed. You can download the plugin here. After you install a plugin, you can check is it installed correctly on Windows Media Player Plugin Test Player (XP/Vista).
<EMBED type="video/x-ms-wmv" width="416px" height="320px" autostart="False" URL="./Movie/Pljacka.wmv" enabled="True" balance="0" currentPosition="0" enableContextMenu="True" fullScreen="False" mute="False" playCount="1" rate="1" stretchTofit="False" uiMode="3">
Media Player Control properties
Available Media Player control properties are shown in table bellow.
Property Default value Description
AudioStream true
AutoSize true
AutoStart true Would movie start when page is loaded
AnimationAtStart true Would animation will play until video file is loaded
AllowScan true
AllowChangeDisplaySize true
AutoRewind false
Balance false
BaseURL
BufferingTime 5
CaptioningID
ClickToPlay true Would Media Player start when user clicks.
CursorType false
CurrentPosition true
CurrentMarker false
DefaultFrame
DisplayBackColor false
DisplayForeColor 16777215
DisplayMode false
DisplaySize false
Enabled true
EnableContextMenu true
EnablePositionControls true
EnableFullScreenControls false
EnableTracker true
Filename URL Set the absolute or relative URL of file to play.
InvokeURLs true
Language true
Mute false
PlayCount 1
PreviewMode false
Rate 1
SAMILang
SAMIStyle
SAMIFileName
SelectionStart true
SelectionEnd true
SendOpenStateChangeEvents true
SendWarningEvents true
SendErrorEvents true
SendKeyboardEvents false
SendMouseClickEvents false
SendMouseMoveEvents false
SendPlayStateChangeEvents true
ShowCaptioning false
ShowControls true Show Media Player controls or not.
ShowAudioControls true Are audio controls visible or not.
ShowDisplay false Is display visible or not.
ShowGotoBar false Is GotoBar visible or not.
ShowPositionControls true
ShowStatusBar false
ShowTracker true
TransparantAtStart false
VideoBorderWidth false
VideoBorderColor false
VideoBorder3D false
Volume -200
WindowlessVideo false
As you can see, Windows Media Player control has many properties. You are not required to set it all. If some property is not used, then control uses its default value. Of course, some property like FileName we must use if we want to play anything.
Custom ASP.NET Media Player Control
Placing static HTML code for Media Player control will not be very efficient method. It is much better to make custom ASP.NET server control which will render correct HTML code depending of property values. This custom control can be used easily by ASP.NET web application, to show play lists, to remember user preferences etc.Control will automatically detect web browser type and render appropriate HTML code.
tag:- How to Place Media Player Control In Mozilla FireFox ,Internet Explorer using ASP.NET
How To Create Thumnail in Asp.NET with C#.NET
//Return thumbnail callback
public bool ThumbnailCallback()
{
return true;
}
///For Image Thumbnail
fileUploadImage : FileUpload Control
m_strRealImagePath : Real Image Path
m_strThumbnailImagePath : Thumbnail Image Path
lblError1 : Label Control
private void MakeThumbnail(string strProductImageName)
{
System.Drawing.Image myThumbnail150;
System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
if (fileUploadImage.PostedFile != null && fileUploadImage.PostedFile.ContentLength > 0)
{
//this code used to remove some symbols between image name and replace with space
string strFileName = fileUploadImage.PostedFile.FileName.Replace('%', ' ').Substring(fileUploadImage.PostedFile.FileName.LastIndexOf("\\") + 1);
string strExtention = System.IO.Path.GetExtension(strFileName);
string imgname1 = strProductImageName.ToString();
string imgname2 = imgname1.Replace('#', ' ').Substring(imgname1.LastIndexOf("\\") + 1);
string imgname3 = imgname2.Replace('@', ' ').Substring(imgname1.LastIndexOf("\\") + 1);
string imgname4 = imgname3.Replace(',', ' ').Substring(imgname1.LastIndexOf("\\") + 1);
string imgname5 = imgname4.Replace('&', ' ').Substring(imgname1.LastIndexOf("\\") + 1);
Finalimagename = imgname5.ToString() + strExtention.ToString();
string imgname = fileUploadImage.PostedFile.FileName.Substring(fileUploadImage.PostedFile.FileName.LastIndexOf("\\") + 1);
string sExtension = imgname.Substring(imgname.LastIndexOf(".") + 1);
///Check File Exists Or Not
if (File.Exists(m_strRealImagePath + Finalimagename))
{
File.Delete(m_strRealImagePath + Finalimagename);
}
//this code is used to check image extension
if (sExtension.ToLower() == "jpg" || sExtension.ToLower() == "gif" || sExtension.ToLower() == "bmp" || sExtension.ToLower() == "jpeg")
{
if (!File.Exists(m_strRealImagePath + Finalimagename))
{
fileUploadImage.PostedFile.SaveAs(ResolveUrl(m_strRealImagePath + Finalimagename));
System.Drawing.Image imagesize = System.Drawing.Image.FromFile(ResolveUrl(m_strRealImagePath + Finalimagename));
Bitmap bitmapNew = new Bitmap(imagesize);
if (imagesize.Width < imagesize.Height)
{
myThumbnail150 = bitmapNew.GetThumbnailImage(150 * imagesize.Width / imagesize.Height, 150, myCallback, IntPtr.Zero);
}
else
{ myThumbnail150 = bitmapNew.GetThumbnailImage(150, imagesize.Height * 150 / imagesize.Width, myCallback, IntPtr.Zero);
}
//Save image in TumbnailImage folder
if (File.Exists(m_strThumbnailImagePath + Finalimagename))
{
File.Delete(m_strThumbnailImagePath + Finalimagename);
}
myThumbnail150.Save(ResolveUrl(m_strThumbnailImagePath) + Finalimagename, System.Drawing.Imaging.ImageFormat.Jpeg);
lblError1.Text = "Successfully uploaded";
imgProductImage.Visible = true;
m_strProductThumbnailImagePath = "~/UserData/ThumbnailImage/"+ Finalimagename;; m_strProductRealImagePath = "~/UserData/RealImage/"+ Finalimagename;
string imgDisplayName = m_strProductThumbnailImagePath;
imgProductImage.ImageUrl = imgDisplayName;
}
}
else
{
lblError1.Visible = true; lblError1.Text = "Check image extension";
}
}
} tag:-How To create thumbnail in asp.net with c#.net,
In PHP three types of strings are using single quoted,double quoted,heredoc
A string literal can be specified in four different ways:
- single quoted
- double quoted
- heredoc
Single quoted
The simplest way to specify a string is to enclose it in single quotes (the character ').
echo 'this is a simple string';echo 'You can also have embedded newlines in strings this way as it isokay to do';// Outputs: Arnold once said: "I'll be back"echo 'Arnold once said: "I\'ll be back"';
<?php
echo 'this is a simple string';
echo 'You can also have embedded newlines in strings this way as it isokay to do';
// Outputs: Arnold once said: "I'll be back"echo 'Arnold once said: "I\'ll be back"';
?>
heredoc
<?php
echo <<<EOT My name is "$name".
I am printing some EOT;?>
A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore
tag:-rDi
fferent types of strings in php - single quoted,double quote,heredoc
Data Types
Booleans
Integers
Floating point numbers
Strings
Variable Declaration
Variables are used for storing a values, like text strings, numbers or arrays.
When a variable is set it can be used over and over again in your script
All variables in PHP start with a $ sign symbol.
The correct way of setting a variable in PHP:
Example :
$txt = "Hello World!";
$number = 16;
tags:-Variable declaration in PHP
Syntax
PHP supports singleline and multipleline comments
//This is a comment
/* This is a comment block */
#This is a comment
tags:-PHP supports singleline and multipleline comments
PHP supports print and echo commands for printing text in a web browser,
Each code line in PHP must end with a semicolon. There are two basic statements to output text with PHP: echo and print. In the example above we have used the echo statement to output the text "Hello World".
echo command
<html>
<body>
<?php print"Helloworld" ?>
</body>
</html>
tag:- PHP : print and echo commands using for print text in a web server
PHP is a powerful server-side scripting language for creating dynamic and interactive websites.PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.PHP is perfectly suited for Web development and can be embedded directly into the HTML code.The PHP syntax is very similar to Perl and C. PHP is often used together with Apache (web server) on various operating systems.
PHP is a powerful tool for making dynamic and interactive Web pages.
PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
In our PHP tutorial you will learn about PHP, and how to execute scripts on your server.
PHP code is executed on the server, and the plain HTML result is sent to the browser.
Basic PHP Syntax
A PHP scripting block always starts with .
A PHP scripting block can be placed anywhere in the document.
tag:-PHP Introduction, PHP Tutorial