Pages

Ads 468x60px

For New Update Use this Link http://dotnethubs.blogspot.in/ Offer for you

.

Monday 6 May 2013

WCF Web Services

Javascript validation for Gridview in edit mode
Categories : - Introduction to WCF  , Differences Between WCF and ASP.NET Web Services,
Basic Step by Step WCF WebService ,

 
Introduction : -Here I will explain what WCF (Windows communication foundation) is, uses of windows communication foundation and how to create and use windows communication foundation in c#.


Description : - In my previous article i have explained Basic Step by Step WCF WebService   in Asp.net. Know i am create a wcf webservice which return the JSON Data.

CREATE A WCF WEB  SERVICE


1. Start Visual Studio 2010

2. Create a new project 
Click on File \ New \ Project.
Make sure WCF is selected in the left part of the window, then select the project type WCF Service Application.
In the Name textbox, type in JSONWebService.
We're going to create a .Net Framework 4.0 web service, so make sure this is selected at the top of the dialog.
Then click on OK.

To do this, we need to make some changes to the sample code. First, we need to change GetData's parameter type from "int" to "string"
Open up the Service1.svc.cs file, and change the "value" parameter to be a string:

Next.....

Friday 3 May 2013

Javascript validation for Gridview in edit mode

Javascript validation for Gridview in edit mode
Categories :- Javascript validation for Gridview footer textbox , Advantages of wcf
 
Introdouction : -

In my Article I am explain how  in can use java script for  validate text box in footer row and check text box in now then generate  the alert please insert Record using  ASp.Net 

Description : -

In My previous Post I have Explained Javascript validation for Gridview footer textbox  in ASp.Net  .There is good source code of  WCF . Now  Java script Validation for Gridview for GridView in Edit Mode.

Here gridview have dropdownlist and two textbox.This javascript validate these fields in edit mode.




function ValidateGridEditMode()
{
var Gid = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer
_gvCustomer').rows.length;
var i;
for(i=2; i <=Gid; i++)
{
if(i<10)
{
ddlCustLocation = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer
_gvCustomer_ctl0'+i+'_ddlCustLocation');
txtCustCode = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer
_gvCustomer_ctl0'+i+'_txtCustCode');
txtCustName = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer
_gvCustomer_ctl0'+i+'_txtCustName');
}

else
{
ddlCustLocation = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer
_gvCustomer_ctl'+i+'_ddlCustLocation');
txtCustCode = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer
_gvCustomer_ctl'+i+'_txtCustCode');
txtCustName = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustome
r_gvCustomer_ctl'+i+'_txtCustName');
}


ddlCustLocation != null || txtCustCode != null || txtCustName != null)
{
ddlCustLocation == 0)
{
alert("Please Select Location..");
ddlCustLocation.focus();
return false;
}
else
{
if(txtCustCode.value == 0)
{
alert("Please enter Customer Code..");
txtCustCode.focus();
return false;
}
else
{
if(txtCustName.value == "")
{
alert("Please enter Customer Name ..");
txtCustName.focus();
return false;
}
}
}
}
}
return true;
}

Javascript validation for Gridview footer textbox

Basic Step by Step WCF WebService[-2]
Introdouction : -

In my Article I am explain how  in can use java script for  validate text box in footer row and check text box in now then generate  the alert please insert Record using  ASp.Net 

Description : -

In My previous Post I have Explain how i can use WCF  . In this article i am explain how  i can validate textbox within grid view and generate the java script validation.

javascript validation function as shown below if you are not use the site  maste page then write this code within <head> tag other wise write this code in
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

Your javascript code is here

</asp:Content>

javascript validation function as shown below

With in site master page



<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

<script type="text/javascript">
    function ValidateGridview() {
        titlename = document.getElementById('<%=((TextBox)grd_party_influenc.FooterRow.FindControl("txt_f_title")).ClientID%>');
        if (titlename.value ==0) {
            alert("Please Insert The Title ....");
            titlename.focus();
            return false;
        }
       // return true;
    }
  
</script></asp:Content>

Use this JavaScript validation within <head> tag

<head>

<script type="text/javascript">
    function ValidateGridview() {
        titlename = document.getElementById('<%=((TextBox)grd_party_influenc.FooterRow.FindControl("txt_f_title")).ClientID%>');
        if (titlename.value ==0) {
            alert("Please Insert The Title ....");
            titlename.focus();
            return false;
        }
       // return true;
    }
  
</script>

</heaad>


Use Java Script Validation Function as shown Below 

  <FooterTemplate>
                        <asp:LinkButton ID="lnk_btn_insert" runat="server" CommandName="Insert" OnClientClick="ValidateGridview()">Insert</asp:LinkButton>
                    </FooterTemplate>

 

Image As Shown Below



Asp.net Interview Question And Answer

Thursday 2 May 2013

gridview rowcommand object reference not set to an instance of an object

Basic Step by Step WCF WebService[-2]
Introduction : -

I am using a gridview with objectdatasource .I have select the data from object datasource but when i insert form gridview i got the error gridview rowcommand object reference not set to an instance of an object.

 Error Page is Here


My gridvew show the all the record from the database as shown in below figure.


Insert the values in textbox


When I insert data in textbox of gridview end click on Insert link then i got the error

Solution :-I am not bind the insert command through the ObjectDataSource like this as shown in figure 

Bind the onbect Data Source Like This Figure
 


Click Next



Click On Fnish Button and Run the Project and you are not getting any error .Data is inserting using gridview successfully as shown  below   figure.



Wednesday 1 May 2013

Basic Step by Step WCF WebService

Basic Step by Step WCF WebService[-2]
Categories :- create restful wcf service api using post ,   Introduction of WCF web service


Introdution- : -
 In my Previous Article I have create restful wcf service api using post and Introduction of WCF web service  In this post i am explain how i can create a WCF service in asp.net and call through windows from


Description : -
Creating a simple 'Hello World'-like WCF service is very simple with Visual Studio 2010. Open Visual Studio 2010 and select New => Project => WCF Service. Name it for example, HelloWorldWCF. It will initially create 2 files for you (IService.cs and IService.svc). Delete them.
Right-click on your project and add a new WCF Service named HW.svc. Your project should look something like this.

Open the IService1.cs  file and modify it so it looks like this.




namespace HelloWorld
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);
     
        [OperationContract]
        float AccountBalance(int AccountNumber);

        // TODO: Add your service operations here
    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}


Then open the Service1.svc.cs file which is the code-behind for the HW.svc file. Modify it so it looks like this. And write the code as shown below



namespace HelloWorld
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : IService1
    {

        public float AccountBalance(int AccountNumber)
        {
            //access a secured database for this.
            if (AccountNumber == 786)
            {
                return 56789.0F;

            }
            else
            {
                return 0.0F;
            }

        }
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }
}


That's it. You have just created your first WCF service. To run it, right-click on the IService1.cs  and select 'Set as Start Page' and then push F5. The WCF Testclient opens up. Double click on the method you just created, enter in a value for the parameter and select the call button.Image As Shown Below

Press F5 for execute the service and you get he following screen


Second Screen Is



Check You WCF Service As shown in figure


Consuming the WCF service from a Windows Form application is just as easy as creating it. In the WCF Testclient, note the http address and port that Visual Studio is using to run you WCF webservice. It may look like this (http://localhost:4428/Service1.svc). You will need this url from within the Windows Form to add a reference to the WCF service.
Open another instance of Visual Studio 2010. Leave the instance you used to created the service open and the personal web service running. If you close it down, you will not be able to access the url above that is running the service.
In the new instance of Visual Studio 2010, select New => Project => Windows Form Application. Add a button and a label to the form. In the Solution explorer, right-click references and select Add Web Resource and enter the url we noted from the WCF Testclient, then Go. Give the service a logical namespace and select ok. In this example I named it AccountBalance.


 Add On Button and One Label on the form as shown below(in this form label is used for display the values)


Write Click on callwcfservice and Add Service Reference As Shown Below




Type The WFC Service Name and click ok as shown below fogure



Your solution explorer should look something like this.


  Lastly, add the code to the button clicked event to call the WCF service.

private void button1_Click(object sender, EventArgs e)
        {
            AccountBalance.Service1Client client =new AccountBalance.Service1Client();
            double message = client.AccountBalance(786);
            lbl_value.Text = message.ToString();

        }

Run the Form and click on Button then You will Get the output of the web service .



If you are like this article then please give me you valuable comment related to this post and mail me if you get any error .

Download sample code attached



Tuesday 30 April 2013

database-normalization

database-normalization

First Normal Form

  • Eliminate repeating groups in individual tables.
  • Create a separate table for each set of related data.
  • Identify each set of related data with a primary key.
Do not use multiple fields in a single table to store similar data. For example, to track an inventory item that may come from two possible sources, an inventory record may contain fields for Vendor Code 1 and Vendor Code 2.

What happens when you add a third vendor? Adding a field is not the answer; it requires program and table modifications and does not smoothly accommodate a dynamic number of vendors. Instead, place all vendor information in a separate table called Vendors, then link inventory to vendors with an item number key, or vendors to inventory with a vendor code key.

Second Normal Form

  • Create separate tables for sets of values that apply to multiple records.
  • Relate these tables with a foreign key.
Records should not depend on anything other than a table's primary key (a compound key, if necessary). For example, consider a customer's address in an accounting system. The address is needed by the Customers table, but also by the Orders, Shipping, Invoices, Accounts Receivable, and Collections tables. Instead of storing the customer's address as a separate entry in each of these tables, store it in one place, either in the Customers table or in a separate Addresses table.

Third Normal Form

  • Eliminate fields that do not depend on the key.
Values in a record that are not part of that record's key do not belong in the table. In general, any time the contents of a group of fields may apply to more than a single record in the table, consider placing those fields in a separate table.

For example, in an Employee Recruitment table, a candidate's university name and address may be included. But you need a complete list of universities for group mailings. If university information is stored in the Candidates table, there is no way to list universities with no current candidates. Create a separate Universities table and link it to the Candidates table with a university code key.

EXCEPTION: Adhering to the third normal form, while theoretically desirable, is not always practical. If you have a Customers table and you want to eliminate all possible interfield dependencies, you must create separate tables for cities, ZIP codes, sales representatives, customer classes, and any other factor that may be duplicated in multiple records. In theory, normalization is worth pursing. However, many small tables may degrade performance or exceed open file and memory capacities.

It may be more feasible to apply third normal form only to data that changes frequently. If some dependent fields remain, design your application to require the user to verify all related fields when any one is changed.

Other Normalization Forms

Fourth normal form, also called Boyce Codd Normal Form (BCNF), and fifth normal form do exist, but are rarely considered in practical design. Disregarding these rules may result in less than perfect database design, but should not affect functionality.

Normalizing an Example Table

These steps demonstrate the process of normalizing a fictitious student table.
  1. Unnormalized table:

    Student#AdvisorAdv-RoomClass1Class2Class3
    1022Jones412101-07143-01159-02
    4123Smith216201-01211-02214-01
  2. First Normal Form: No Repeating Groups

    Tables should have only two dimensions. Since one student has several classes, these classes should be listed in a separate table. Fields Class1, Class2, and Class3 in the above records are indications of design trouble.

    Spreadsheets often use the third dimension, but tables should not. Another way to look at this problem is with a one-to-many relationship, do not put the one side and the many side in the same table. Instead, create another table in first normal form by eliminating the repeating group (Class#), as shown below:

    Student#AdvisorAdv-RoomClass#
    1022Jones412101-07
    1022Jones412143-01
    1022Jones412159-02
    4123Smith216201-01
    4123Smith216211-02
    4123Smith216214-01         
  3. Second Normal Form: Eliminate Redundant Data
    Note the multiple Class# values for each Student# value in the above table. Class# is not functionally dependent on Student# (primary key), so this relationship is not in second normal form.

    The following two tables demonstrate second normal form:

    Students:

    Student#AdvisorAdv-Room
    1022Jones412
    4123Smith216


    Registration:

    Student#Class#
    1022101-07
    1022143-01
    1022159-02
    4123201-01
    4123211-02
    4123214-01
  4. Third Normal Form: Eliminate Data Not Dependent On Key

    In the last example, Adv-Room (the advisor's office number) is functionally dependent on the Advisor attribute. The solution is to move that attribute from the Students table to the Faculty table, as shown below:

    Students:

    Student#Advisor
    1022Jones
    4123Smith


    Faculty:

    NameRoomDept
    Jones41242
    Smith21642

Monday 29 April 2013

change text box border color css using jquery asp.net

change text box border color css using jquery asp.net
Introduction : -
Here i will explain how i can change the boder color of textbox after insert the number using Jquery in Asp.Net   In My Previous Article I have Provide  jQuery Restrict to Allow Only Numbers in Textbox in Asp.net .

Description : -
In previous posts I explained  I have Explain create simple drop down menu using jquery ,Simple Menu using Jquery step by step  Now   I will expplain how to allow only numbers or numeric characters in textbox using Jquery  in Asp.net .

Jquery Scripts As Shown Below for Change the textbox Border Color in asp.net

Note :- I am  using visual stdio 2010 show i  include the jquey in my page form the scripts folder




<head runat="server">
    <title>Change textbox color on insert the any alfa numeric values</title>
    <script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>

<!--change the border color color of textbox-->
    <script type="text/javascript" language="javascript">
        debugger;
        $(document).ready(function () {
            $(".txt1").keypress(function () {
                var str = /^[0-9a-zA-Z]+$/;
                var value = $(this).val();
                if (!str.test(value)) {
                    $(".txt1").css({ borderColor: 'Red' });
                }
                else {
                    $(".txt1").css({ borderColor: 'Green', BorderWidth: '3px' });
                }

            }).keypress();
        });
</script>

<script type="text/javascript">

    $(document).ready(function () {

        $(".txt2").keypress(function () {

            var str2 = /^[0-9a-zA-Z]+$/;
            var value = $(this).val();
            if (!str2.test(value)) {
                $(".txt2").css({ borderColor: 'red' });
            }
            else {
                $(".txt2").css({ borderColor: 'Green', BorderWidth: '2px' });
            }
        });
    });

</script>

</head>

Asp.net Text Box Controll On the Form As shown Below






<body>
<center>
    <form id="form1" runat="server">
    <div>
        Name&nbsp;&nbsp; :&nbsp; <asp:TextBox ID="txt2" runat="server" BorderWidth="2px" class="txt2"></asp:TextBox><br/><br/>
    Password :&nbsp; <asp:textbox id="txt1" runat="server" borderwidth="1px" class="txt1"></asp:textbox>
    </div>
    </form>
    </center>
</body>


 Output Windows as shown below



Download sample code attached



Implicit conversion from data type varchar to varbinary is not allowed

Implicit conversion from data type varchar to varbinary is not allowed [Error Solution]
Error :-Implicit conversion from data type varchar to varbinary is not allowed

Solution :- This Problem Occur when we define the wrong data type declaration for create the table 
Example as Shown Below




CREATE TABLE [dbo].[issue_tab](
 [id] [int] IDENTITY(1,1) NOT NULL,
 [name] [varchar](255) NULL,
 [party] [varchar](255) NULL,
 [address] [text] NULL,
 [related_person] [varchar](255) NULL,
 [type_selection] [varchar](255) NULL,
 [contactno] [VARBINARY(MAX)](10) NULL,
 CONSTRAINT [PK_issue_tab] PRIMARY KEY CLUSTERED 
(
 [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF
, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON,
 ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

In this Above table Lock at the highlight contactno coloumn .The datatype is[VARBINARY(MAX)](10) NULL show we get the error .

Result : - So Change the Data Type Like Varchar and According to You Want to Enter From the Form



CREATE TABLE [dbo].[issue_tab](
 [id] [int] IDENTITY(1,1) NOT NULL,
 [name] [varchar](255) NULL,
 [party] [varchar](255) NULL,
 [address] [text] NULL,
 [related_person] [varchar](255) NULL,
 [type_selection] [varchar](255) NULL,
 [contactno] [varchar]](255) NULL,
 CONSTRAINT [PK_issue_tab] PRIMARY KEY CLUSTERED 
(
 [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF
, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON,
 ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
---------------------------------------------------------------------------------------------------------

jQuery Restrict to Allow Only Numbers in Textbox in Asp.net

create simple drop down menu using jquery
Introduction : -
Here I will explain how to allow only numbers or numeric characters in textbox using JQuery in asp.net.with error message 

Description :- 
In previous posts I explained  I have Explain create simple drop down menu using jquery ,Simple Menu using Jquery step by step  Now   I will expplain how to allow only numbers or numeric characters in textbox using JQuery in asp.net.

To restrict user to enter only number in textbox we write the following code as shown below

Jquery code as shown below

 Code is Here




<head runat="server">
    <title>jquery text box valiation only enter the number</title>
    <script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
    //called when key is pressed in textbox
            $("#quantity").keypress(function (e) {
                //if the letter is not digit then display error and don't type anything
                if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                    //display error message
                    $("#errmsg").html("Digits Only").show().fadeOut("slow");
                    return false;
                }
            });
        });
 
    </script>
    <style type="text/css">
    #errmsg
    {
        color:Red;
    </style>

  
</head>

asp.net  form code here
 Code is Here




<body>
    <form id="form1" runat="server">
    <div>
   Number : <input type="text" name="quantity" id="quantity" />&nbsp;<span id="errmsg"></span><br /><br/>
 
    </div>
    </form>
</body>

After Write Code The Page Is Shown Below



Download sample code attached






Simple Menu using Jquery Beginners Tutorial , create simple drop down menu using jquery

Friday 26 April 2013

create simple drop down menu using jquery

create simple drop down menu using jquery
Introduction : -

While creating menus, the most preferred method is to use some sort of lists which will ease in standardization of the thing. This way styling with CSS become more easier and powerful. For a complete reference of how lists work check this link for reference.

You can see a demo of resultant menu here


Thursday 25 April 2013

Introduction to WCF

onclick checkbox select data from gridview asp.net
Introduction :-

Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.
Below figures shows the different technology combined to form WCF.





Advantage

  1. WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net.
  2. WCF services provide better reliability and security in compared to ASMX web services.
  3. In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
  4. WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.

Disadvantage

Making right design for your requirement is little bit difficult. I will try to help you on solving these difficulties in the following article.

onclick checkbox select data from gridview asp.net

onclick checkbox select data from gridview asp.net
 Introduction : -

In this Tutorial when user select the one or multipal  checkbox  from the gridview and show the values on the form.

Description : -
 
In my Previous article i have provided the asp.net interview questions with answers for 2 years experience  Ajax AsyncFileUpload control example in asp.net to upload files to server   jquery form validation in asp.net  I have Provide the More Difference b/w Differences Between WCF and ASP.NET Web Services   and also provide the  create restful wcf service api using post step by step
To get checkbox selected row values from gridview we need to write the code like this


C# Code

foreach(GridViewRow  gvrow in gvDetails.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
if (chk != null & chk.Checked)
{
str += gvDetails.DataKeys[gvrow.RowIndex].Value.ToString() + ',';
strname += gvrow.Cells[2].Text+',';
}
}
If you want to see complete example we need to write the following code in aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript" language="javascript">

        function ConfirmOnDelete(item) {

            if (confirm("Would you like to delete selected item(s)?") == true)

                return true;

            else

                return false;

        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:GridView ID="gvDetails" DataKeyNames="UserId" AutoGenerateColumns="False"
            CellPadding="4" runat="server" ForeColor="#333333" GridLines="None">
          <AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
          <EditRowStyle BackColor="#7C6F57" />
          <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="true" ForeColor="White" />
          <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
          <RowStyle BackColor="#E3EAEB" />
          <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
          <SortedAscendingCellStyle BackColor="#F8FAFA" />
          <SortedAscendingHeaderStyle BackColor="#246B61" />
          <SortedDescendingCellStyle BackColor="#D4DFE1" />
          <SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
<asp:Button ID="btnProcess" Text="Get Selected Records" runat="server"
Font-Bold="true" onclick="btnProcess_Click" /><br />
<asp:Label ID="lblmsg" runat="server" />
    </div>
    </form>
</body>
</html>

Now in code behind add the following namespaces

C# Code

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
Now add below code in code behind

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridviewData();
        }
  
    }

     protected void BindGridviewData()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Education", typeof(string));
dt.Columns.Add("Location", typeof(string));
DataRow dtrow = dt.NewRow();    // Create New Row
dtrow["UserId"] = 1;            //Bind Data to Columns
dtrow["UserName"] = "chitranjan";
dtrow["Education"] = "M.C.A";
dtrow["Location"] = "Indore";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();               // Create New Row
dtrow["UserId"] = 2;               //Bind Data to Columns
dtrow["UserName"] = "Aman";
dtrow["Education"] = "B.E";
dtrow["Location"] = "Pune";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();              // Create New Row
dtrow["UserId"] = 3;              //Bind Data to Columns
dtrow["UserName"] = "Rahul";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Bombai";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();              // Create New Row
dtrow["UserId"] = 4;              //Bind Data to Columns
dtrow["UserName"] = "Amar";
dtrow["Education"] = "B.E";
dtrow["Location"] = "Bhopal";
dt.Rows.Add(dtrow);

gvDetails.DataSource = dt;
gvDetails.DataBind();
}


     protected void btnProcess_Click(object sender, EventArgs e)
     {
         string str = string.Empty;
         string strname = string.Empty;
         foreach (GridViewRow gvrow in gvDetails.Rows)
         {
             CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
             if (chk != null & chk.Checked)
             {
                 str += gvDetails.DataKeys[gvrow.RowIndex].Value.ToString() + ',';
                 strname += gvrow.Cells[2].Text + ',';
             }
         }
         str = str.Trim(",".ToCharArray());
         strname = strname.Trim(",".ToCharArray());
         lblmsg.Text = "Selected UserIds: <b>" + str + "</b><br/>" + "Selected UserNames: <b>" + strname + "</b>";
     }
Screen Short as shown below

After Select Check Box Show The Data


Download sample code attached

Tuesday 23 April 2013

mongodb upload image using php

mongodb upload image using php
Categories :- What is Mongodb  Install Mongo on CentOS,Fedora, Ubuntu & Debian


Introduction : - In My privous article i have explained  What is Mongodb
GridFS is a specification for storing large files in MongoDB. In this post I will explain how you can easily upload a file to GridFS and then retrieve it from the database to serve it to the browser

The name of the uploaded file to store. This should correspond to the file field's name attribute in the HTML form
<html>
<body>
<!--The name of the uploaded file to store. This should correspond to the file field's name attribute in the HTML form. -->
<form method="POST" enctype="multipart/form-data">
    <label for="username">Username:</label>
    <input type="text" name="username" id="username" />
    <label for="pic">Please upload a profile picture:</label>
    <input type="file" name="pic" id="pic" />
    <input type="submit" />
</form>

</html></body>

If you wanted to store the uploaded image in MongoDB, you could do the following in the script handling the form submission:

<?php
error_reporting(0); //// Turn off all error reporting
//If you wanted to store the uploaded image in MongoDB, you could do the following in the script handling the form submission:
$m = new MongoClient();
$gridfs = $m->selectDB('test')->getGridFS();

$gridfs->storeUpload('pic', array('username' => $_POST['username']));
echo 'File Uploaded Successfully';

?>

Complete Code As Show Below

<!-- image and any file  uploaded  in mongodb -->
<html>
<body>
<!--The name of the uploaded file to store. This should correspond to the file field's name attribute in the HTML form. -->
<form method="POST" enctype="multipart/form-data">
    <label for="username">Username:</label>
    <input type="text" name="username" id="username" />
    <label for="pic">Please upload a profile picture:</label>
    <input type="file" name="pic" id="pic" />
    <input type="submit" />
</form>

</html></body>

<?php
error_reporting(0); //// Turn off all error reporting
//If you wanted to store the uploaded image in MongoDB, you could do the following in the script handling the form submission:
$m = new MongoClient();
$gridfs = $m->selectDB('test')->getGridFS();

$gridfs->storeUpload('pic', array('username' => $_POST['username']));
echo 'File Uploaded Successfully';

?>

Running output Image Screen Short As shown Below
1-> Run the Fie then

2-> when insert the Name and Browse the Image Screen Short As Show Below

3-> When Click on Submit  Query Button Get the Message (File Uploaded Successfully)


 4-> Check the Out In Database Image is Save or not open the genghis phpadmin then output as shown below




Download sample code attached



 

..




New Updates

Related Posts Plugin for WordPress, Blogger...

Related Result