-->

Friday, May 23, 2014

How to get total days of month in asp.net c#

If you want to find total days in current month then you should use DayInMonth( ) method of DateTime structure. In this method you should pass the year and month, which you want to access total days of the month. Lets take an simple example to find total days of a month

Source Code

<form id="form1" runat="server">
    <div>  
        <asp:Button ID="Button1"
         runat="server"
         BackColor="#99CCFF"
         onclick="Button1_Click"
         Text="Click" />  
    </div>
       <asp:Label ID="Label1"
       runat="server"
       BackColor="#FFFF66"
       Text="Label"></asp:Label>
    </form>

Code Behind

protected void Button1_Click(object sender, EventArgs e)
        {          
            DateTime today = DateTime.Today;          
            int TotalOfDays = DateTime.DaysInMonth(today.Year, today.Month);
            Label1.Text = "today : " + today.ToLongDateString();
            Label1.Text += "<br /><br />Total days in month=";
            Label1.Text += TotalOfDays;

        }  
Code Generate the following output
How to get total days of month in asp.net c#

Thursday, May 22, 2014

How to make video and mp3 player in windows form c#

If you want to play audio file and video file in windows form c# project then you should go for windows media player control. This is unchecked component of toolbox bydefault. If you want to add media player into the list , check my previous article.
There are various step to design player in windows form, these are:
Step-1: Add menuStrip control on the form, add 'File' text in it as a root also design sub child of the root item like 'open' and 'add to the playlist'. Looking like

menuStrip control with items


Step-2 : Add Windows media player and ListBox on the form also set the properties of both controls
Window Media Player control --Name property = WindowsMediaPlayer1
ListBox Control -- Name property= listBox1

Step-3 : Double click on Open file menu item and handle raised event, also double click on Add to Playlist menu item.
Step-4 : Copy the code and use it
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace mediaplayer
{
    public partial class Form1 : Form
    {
        string[] path, filename;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog filedialog = new OpenFileDialog();
            if (filedialog .ShowDialog ()==DialogResult.OK)
            {
                WindowsMediaPlayer1.URL = filedialog.FileName;
                WindowsMediaPlayer1.Ctlcontrols.play();
                
            }
        }

        private void createPlaylistToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog filedialog = new OpenFileDialog();
            filedialog.Multiselect = true;
            if (filedialog .ShowDialog ()==DialogResult .OK)
            {
                filename = filedialog.SafeFileNames;
                path = filedialog.FileNames;
                for (int i = 0; i < filename.Length; i++)
                {
                    listBox1.Items.Add(filename[i]);
                    
                }
                
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            WindowsMediaPlayer1.URL = path[listBox1.SelectedIndex];
        }
    }
}
Code Generate the following output
How to make video and mp3 player in windows form c#

Tuesday, May 20, 2014

How to add Windows media player in toolBox windows form c#

Winforms toolbox does not contain windows media player bydefault. Suppose, you want to make video and mp3 player in c# then you should go for media player, which is not exist in toolbox. If you want to add it into the toolBox then follow these steps, which is given below.

If your toolbox does not contain media player

Step-1 : Right click on toolbox and select choose items..

choose items in vs toolbox
Step-2 : Now, appear a new window, select com component tab also check window media player in the list
select com component tab also check window media player in the list
Step-3 : Press 'ok button' and check window media player in the toolbox.
 window media player in the toolbox

Monday, May 19, 2014

Count number of visitor on website in asp.net c#

Introduction

If you want to count visitors, which is appear on your website. You can use Global.asax file for counting visitors. Google analytical tool is the best tool to count numbers of visitors, who is visit the site. I have simple demonstration of google analytical is:


  Now, create the simple code into c# for counting visitors.
Step-1 : Add Global.asax file into the project.
Step-2 : Add this code into  Application_Start block.

Application["visitcount"] = 0;

// In this code we create a application object, which hold 0. When application start by the server , This method is run once at a time.
Step-3 : Also add this code into Session_Start block.
 // Code that runs when a new session is started
        Application.Lock();
        Application["visitcount"] = (int)Application["visitcount"] + 1;
        Application.UnLock();
//  This method is raise on every post back event. The first line of code that is Application.Lock() define, only one client can access or modify the variable, which is stored in application object. The second line of code that is (Application["visitcount"] = (int)Application["visitcount"] + 1;) define, a application object incremented by one. In third line, locked application object will be unlocked.
Step-4 : Add new webform into the project, also take a label control on it.
Step-5 : On page_load event take the application object value onto the label text.

Complete Source code

<form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server"></asp:Label>
    </div>
    </form>
Code Behind
 protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = Application["visitcount"].ToString();
    }
Global.asax file code
<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        Application["visitcount"] = 0;

    }
    
    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown

    }
        
    void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs

    }

    void Session_Start(object sender, EventArgs e) 
    {
        // Code that runs when a new session is started
        Application.Lock();
        Application["visitcount"] = (int)Application["visitcount"] + 1;
        Application.UnLock();

    }

    void Session_End(object sender, EventArgs e) 
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.

    }
       
</script>
Now, run the application. Code generate the following output
Count number of visitor on website in asp.net c#

Sunday, May 18, 2014

How to Retrieve XML Data from a Database Table: SQL

At times, you need to retrieve the relational data from a table into the XML format for reporting purposes or to share the data across different applications. This involves extracting data from a table in the form of well-formed XML fragments. You can retrieve the XML data in the following ways:

Using the FOR XML Clause in the SELECT statement

SQL Server allows you to extract data from relational tables into an XML format by using the SELECT statement with the FOR XML clause. You can use the FOR XML clause to retrieve the XML data by using the following modes:
  • RAW
  • AUTO
  • PATH
  • EXPLICIT

Using the RAW Mode

The RAW mode is used to return an XML file with each row representing an XML element. The RAW mode transforms each row in the query result set into an XML element with the element name row. Each column value that is not NULL is mapped to an attribute with the same name as the column name.

The following statements display the details of employees with employee ID as 1 or 2:
SELECT EmployeeID, ContactID, LoginID, Title
FROM HumaneResources.Employee
WHERE EmployeeID=1 OR EmployeeID=2
FOR XML RAW

The preceding query displays the employee details in the following format:

<row EmployeeID=”1” ContactID=”1209” LoginID=”adventure-works/guy1” Title=”Production Technician – WC60” />
<row EmployeeID=”2” ContactID=”1030” LoginID=”adventure-works/kevin0” Title=”Marketing Assistant” />

Using the AUTO Mode

The AUTO mode is used to return query results as nested XML elements. Similar to the RAW mode, each column value that is not NULL is mapped to an attribute that is named after either the column name or the column alias. The element that these attributes belong to is named to the table that they belong to or the table alias that is used in the SELECT statement, as shown in the following query:

SELECT EmployeeID, ContactID, LoginID, Title
FROM HumanResources.Employee Employee
WHERE EmployeeID=1 OR EmployeeID=2
FOR XML AUTO

If the optional ELEMENTS directive is specified in the FOR XML clause, the columns listed in the SELECT clause are mapped to sub-elements, as shown in the following query:

SELECT EmployeeID, ContactID, LoginID, Title
FROM HumanResources.Employee Employee
WHERE EmployeeID=1 OR EmployeeID=2
FOR XML AUTO, ELEMENTS

Using the PATH Mode

The PATH mode is used to return specific values by indicating the column names for which you need to retrieve the data, as shown in the following query:

SELECT EmployeeID “@EmpID”,
FirstName “EmpName/First”,
MiddleName “EmpName/Middle”,
LastName “EmpName/Last”
FROM HumanResources.Employee e JOIN Person.Contact c
AND e.EmployeeID=1
FOR XML PATH

The preceding query displays the output in the following format:
<row EmpID=”1”>
<EmpName>
<First>Guy</First>
<Middle>R</Middle>
<Last>Gilbert</Last>
</Employee>
</row>

In the preceding result set, the EmployeeID column is mapped to the EmpID attribute with @ sign. The FirstName, MiddleName, and LastName columns are mapped as subelements of the EmpName element with the slash mark(/)

You can also use the optional ElementName argument with the PATH mode query to modify the name of the default row element, as shown in the following query:

SELECT EmployeeID “@EmpID”,
FirstName “EmpName/First”,
MiddleName “EmpName/Middle”,
LastName “EmpName/Last”
FROM HumanResources.Employee e JOIN Person.Contact c ON e.ContactID = c.ContactID
AND e.EmployeeID=1
FOR XML PATH (‘Employee’)

Using the EXPLICIT Mode

The EXPLICIT mode is used to return an XML file that obtains the format as specified in the SELECT statement. Separate SELECT statement can be combined with the UNION ALL statement to generate each level/element in the resulting XML output. Each of these SELECT statements requires the first two tags to be called Tag and Parent. The Parent element is used to control the nesting of elements. It contains the tag number of the parent element of the current element. The top-level element in the document should have the Parent value set to 0 or NULL.

For example, the managers of AdventureWorks want to access the information regarding products through their mobile devices. These devices cannot directly connect to the SQL Server, but can read the data provided in the XML format. Therefore, you need to convert the details of the products from the Product table into the XML document. To perform this task, you need to create an XML document with <Product> as the parent tag. The <Product> tag will contain ProductID as an attribute and <ProductName> and <Color> as child elements.

To perform this task, the database developer can create the following query:

SELECT 1 AS Tag,
NULL AS Parent,
ProductID AS [Product!1!ProductID],
Name AS [Product!1!ProductName!element],
Color AS [Product!1!Color!elementxsinil]
FROM Production.Product
FOR XML EXPLICIT

How to Store Typed XML Data in XML Columns: SQL

To store the typed XML data, programmer need to first register the schema associated with the data in the XML schema collection objects in the database. The XML schema collection is an object on the SQL Server that is used to save one or more XML schemas. You can create an XML schema collection object by using the following SQL statement:

CREATE XML SCHEMA COLLECTION <Name> as Expression
Where,

  • Name specifies an identifier name with which the SQL Server will identify the schema collection.
  • Expression specifies an XML value that contains one or more XML schema documents

For example, the customer details are associated with the following schema:
<?XML version=”1.0” ?>
<xsd:schema targetNamespace=”http//schemas.adventure-
Works.com/Customers” xmlns=”http//shemas.adventure-
Works.com/Customers” elementFormDefault=”qualified”
attributeFormDefault=” unqualified”
xmlns:xsd=”http://www.w3.org/2001/XMLSchema”?>
<xsd:element name =”Customer” type=”xsd:string” />
<xsd:attribute name=”City” type=”xsd:string” />
</xsd:schema>

You can use the following statements to register the preceding schema, named as CustomerSchemaCollection, with the database:

CREATE XML SCHEMA COLLECTION CustomerSchemaCollection AS n’<?xml version= “1.0” ?>
<xsd:schema targetNamespace=”http://schemas.adventure-
Works.com/Customers” xmlns=”http://schemas.adventure-
Works.com/Customers” elementFormDefault=”qualified”
attributeFormDefault=”unqualified”
xmlns:xsd=”http://www.w3.org/2001/XMLSchema”.>
<xsd:element name =”Customer” type=”xsd:string” />
<xsd:attribute name=”Name” type=”xsd:string” />
<xsd:attribute name=”City” type=”xsd:string” />
</xsd:schema>’

You can view information about the registered schemas in a database by querying the sys.XML_schema_collection catalog view, as shown in the following statement:
SELECT * FROM sys.XML_schema_collections
After registering the XML schema, you can use the schemas to validate typed XML values while inserting records into the tables. You need to specify this while creating a table that will store the XML data. In the preceding example, if you need to validate the customer details with the CustomerSchemaCollection schema, you need to create the CustDetails table by using the following statement:

CREATE TABLE CustDetails
(
CustID int,
CustDetails XML
)

You can insert data into this table by using the following statement:
INSERT INTO CustDetails VALUES (2, ‘<?xml version=”1.0”?> <CustomerName=”Abrahim Jones” City=”Selina” />’)

While executing the preceding statement, the SQL Server will validate the values for the CustDetails column against the CustomerSchemaCollection schema.

How to Store XML Data in XML Columns: SQL

At times, Programmer need to store the XML data in its original state in a column of a database table. For example, you need to save the details of customers in the database. The details of individual customers are maintained by a website. The website saves the details of each customer in an XML file. As a database developer, you need to save this data in the SQL Server. For this, you can create the following table to store the customer details:

CREATE TABLE CustDetails ( CUST_ID int, CUST_DETAILS XML )

You can save the following types of data in the columns with the XML data types:
Untyped XML data: is also a well-formed data, but is not associated with a schema. The SQL Server does not validate this data, but ensures that the data being saved with the XML data type is well-formed.

Typed XML data: is a well-formed data that is associated with a schema defining the elements and their attributes. It also specifies a namespace for the data. When you save the typed XML data in a table, the SQL Server validates the data against the schema and assigns the appropriate data type to the data based on the data types defined in the schema. This helps in saving the storage space.
As a database developer, you should know how to store both types of data on the SQL Server.

Staring Untyped XML Data

To store the untyped XML data, you can use columns or variables with the XML data type. For example, to store customer data in the CustDetails table, you can use the following INSERT statement:

INSERT INTO CustDetails VALUES (2, ‘<Customer Name=’Abrahim Jones” City= “Selina” />’)

In the preceding statement, the string value that contains an XML fragment is implicitly converted to XML. However, you can also convert a string value to XML by using the CONVERT or CAST functions. In this example, you can use the following statement to convert the data type of the string value to XML before inserting the record into the table.

INSERT INTO CustDetails VALUES (2, convert (XML, ‘<CustomerName=”Abrahim Jones” City=”Selina” />’) )

Similarly, you can also use the CAST function, as shown in the following statement:

INSERT INTO CustDetails VALUES (4, cast (‘<Customer Name=”Abrahim Jones” City=”Selina” />’ as XML) )

© Copyright 2013 Computer Programming | All Right Reserved