Software Programs and Projects

This Software Programs and Projects include programing tips and technology using different languages like VC++,ASP,JSP C#.Net,PHP,VB.Net,JavaScript,ASP.NET .Software Programs and Projects blog mainly support to software programmers and provide help through the mail.

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:

<?php echo "<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 names define("FOO", "something"); define("FOO2", "something else"); define("FOO_BAR", "something more"); // Invalid constant names define("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 is okay 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 is okay 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

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


print command


<html>
<body>
<?php print"Helloworld" ?>
</body>
</html>

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


Example "Hello World"

"

echo "Hello World";
?>

"

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

//Checking Listbox item selected or not in C#.Net
//Selected ListBox Item Value and Text

if (this.listBoxExistingDestination.SelectedIndex != -1)
{
//Selected ListBox Item Value and Text
int iDestinationId = (int)this.listBoxExistingDestination.SelectedValue;
string strDestinationName=this.listBoxExistingDestination.Text;
}
else
{
//Unselect
}

the same code using for Dropdownlist control in C#.NET windows based application

tag:-Check if Item selected in Listbox : C#.Net

Related Posts

#region Function to check if a value is numeric

public static bool IsNumeric(string strValue)
{
int iCount = 0;
int iValue;
if (string.IsNullOrEmpty(strValue))
{
iCount = 0;
}
else
{
foreach (char cCharacter in strValue)
{
if (int.TryParse(Convert.ToString(cCharacter), out iValue))
{
iCount += 1;
}
else
{
iCount = 0;
return false;
}
}
}
if (iCount > 0)
return true;
else
return false;
}
#endregion

tag-:Check numeric in C#.NET

How can clear listbox control selection using C#.Net

#region Clear Listbox Control

private void ClearListBoxControlSelection(ListBox listBoxItem)
{
for (int iIndex = 0; iIndex < listBoxItem.Items.Count; iIndex++)
{
listBoxItem.SetSelected(iIndex, false);
}
}

#endregion


tags:- How can clear listbox controls selection in C#.Net

In everyday life when we deal with time, we speak in seconds, minutes, hours, days, weeks, months, years, decades, centuries, etc.... you get the idea. When PHP deals with time it uses only one measurement, seconds. More specifically it measures time in seconds since January 1, 1970. Once we know how time works in PHP, it becomes easier to add, subtract, and calculate time. Below is a quick guide:

Time in Seconds
1 Minute: 60 seconds
1 Hour: 3,600 seconds
1 Day: 86,400 seconds
1 Week: 604,800 seconds
4 Weeks: 2,419,200 seconds
1 Year: 31,536,000 seconds
1 Decade: 315,360,000 seconds

Now let's put this into practice. Let's say for example you wanted to set a cookie in a user's browser to expire in one year. The way we would calculate this is by adding one year, or 31,536,000 seconds to the current date before setting the cookie:

$Year = 31536000 + time() ;
Perhaps you want to find out what calendar day occurs in a set period of time. This is what is done in pregnancy calendars. In this example we will find the calendar date that occurs in exactly 2 weeks (1209600 seconds) time. $twoweeks = 1209600 + time() ;
echo date("M-d-Y", $twoweeks) ;