DotNet Friends

Amit Patriwala

Calling Web service from Flex – Part 1

Here I am Explain how to use Web Services in Flex Application.

Steps:

1) First we create web service in Asp.net with C#. create new Web method in Web service is GetName.

[WebMethod]
    public string GetName(string UserName)
    {
        return "WelCome  " + UserName;
    }

My web service name is WebServices.

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }
    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
    [WebMethod]
    public string GetName(string UserName) {
        return "WelCome  " + UserName;
    }
}

2) Open Flex Application.

3) Put below control in to application.

    3.1)  WebService (ID =MyWebService)

    3.2) Label for display Information

    3.3) TextArea (ID=txtUserName) – get value and pass value in to WebService

    3.4) Button (ID=btnSubmit) – Call Web service

    3.5) TextArea (ID=txtResult) – Display result from Web service

Application Page Info.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<!--Web Service Information
wsdl  URL of Web Service
fault  if any error loading web service
operation  method name in Webservices
request  pass the parameter to Webservices
*here I get the TextBox Value
-->
<mx:WebService id="MyWebService" wsdl="http://localhost:3549/ChangeWebConfigFile/WebService.asmx?WSDL"
    fault="mx.controls.Alert.show(event.fault.faultString)" >
    <mx:operation name="GetName">
        <mx:request>
        <UserName>{txtUserName.text}</UserName>
        </mx:request>
    </mx:operation>
</mx:WebService>
<mx:VBox>

    <mx:Label text="Enter User Name">
    </mx:Label>
    <mx:TextArea id="txtUserName" text="test">
    </mx:TextArea>

    <mx:Button id="btnSubmit" label="Submit.." click="checkUserName();">
    </mx:Button>
    <mx:TextArea id="txtResult"/>
</mx:VBox>
<mx:Script>
    <![CDATA[
      private function checkUserName():void
    {
        MyWebService.GetName.send();
        txtResult.text= MyWebService.GetName.lastResult;
    }
    ]]>
</mx:Script>
</mx:Application>

4) Run Flex Application.

 

image

 

 

thnx

June 23, 2009 Posted by patriwala | Asp.Net 2.0, Flex | | No Comments Yet

Error #1085: The element type "p" must be terminated by the matching end-tag "</p>" in Flex

I have got this Error when I used asp.net web services in FLEX. I found Solution which is mention below.

Steps:

1) Check the URL of your Web Services

    you can put direct URL of Web services here I am used URL is  http://localhost:3549/ChangeWebConfigFile/WebService.asmx and got Error.

2)

change in URL http://localhost:3549/ChangeWebConfigFile/WebService.asmx?WSDL and solve the Error.

thnx

June 23, 2009 Posted by patriwala | Flex | | No Comments Yet

Convert Generic List In To DataTable

Create simple asp.net application with C#. Add new class (GenericToDataTable).

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

public class GenericToDataTable
{
/// <summary>
/// Default Constructor
/// </summary>
private GenericToDataTable()
{ }
/// <summary>
///
/// </summary>
/// <typeparam name=”T”>Custome Class </typeparam>
/// <param name=”lst”>List Of The Custome Class</param>
/// <returns> Return the class datatbl </returns>
public static DataTable ConvertTo<T>(IList<T> lst)
{
//create DataTable Structure
DataTable tbl = CreateTable<T>();
Type entType = typeof(T);

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
//get the list item and add into the list
foreach (T item in lst)
{
DataRow row = tbl.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
tbl.Rows.Add(row);
}

return tbl;
}

/// <summary>
///
/// </summary>
/// <typeparam name=”T”>Custome Class</typeparam>
/// <returns></returns>
public static DataTable CreateTable<T>()
{
//T –> ClassName
Type entType = typeof(T);
//set the datatable name as class name
DataTable tbl = new DataTable(entType.Name);
//get the property list
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
foreach (PropertyDescriptor prop in properties)
{
//add property as column
tbl.Columns.Add(prop.Name, prop.PropertyType);
}
return tbl;
}
}

after add above class compile the code.

after compilation add new class into project (Class Name: clsUser).

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;

/// <summary>
/// Summary description for clsUser
/// </summary>
public class clsUser
{
//create property userid
private int _UserId;
public int UserID
{
get { return _UserId; }
set { _UserId = value; }
}
//create property username
private string _UserName;
public string UserName
{
get { return _UserName; }
set { _UserName = value; }
}
/// <summary>
/// Default Constructor
/// </summary>
public clsUser()
{ }

public clsUser(int userid,string username)
{
this.UserID = userid;
this.UserName = username;
}
}

After adding this class into project go to Default.aspx page in this page type below code on Page Load event.

//create generic list of class clsUser
System.Collections.Generic.List<clsUser> obj = new
System.Collections.Generic.List<clsUser>();
//add data into list
for (int i = 0; i < 10; i++)
{
obj.Add(new clsUser(i,”a”+i.ToString()));
}
//convert list to datatable
DataTable dt= GenericToDataTable.ConvertTo<clsUser>(obj);

now check the DataTable(dt).

thnx

December 3, 2008 Posted by patriwala | Asp.Net 2.0, C#.net, WindowsApplication, dotnet | , , , , , | 8 Comments

Get Parameter List from StoreProcedure or Function in SqlServer 2005

–get all storeprocedure and function

SELECT * FROM INFORMATION_SCHEMA.PARAMETERS

–pass storeprocedure name or function name

–get the relavent columns ParameterName,DataType,Length,ParameterType

SELECT Parameter_name as ParameterName,Data_type as DataType,coalesce(Character_Maximum_Length,0) as Length,Parameter_Mode as ParameterType FROM INFORMATION_SCHEMA.PARAMETERS

WHERE SPECIFIC_NAME=’sp_InsertOrder’

October 11, 2008 Posted by patriwala | Database, SqlServer | | 1 Comment

Get Primary key – Foreign key relations table in sql server 2005

Why it is required?

The main purpose of this is finding related constraint table from database.

Check below Query.

–get table list with constraint(primary and foreign key)

select * from information_schema.constraint_column_usage

–get table list with foreign key constraint

select * from information_schema.referential_constraints

–get the relation

select

tblAll.table_name as PrimaryTableName,

tblAll.column_name as PrimaryTableColumn,

tblFK.table_name as ForeignKeyTable,

tblFK.column_name as ForeignKeyColumn

from information_schema.constraint_column_usage tblAll

inner join information_schema.referential_constraints tblAllFK on tblAllFK.unique_constraint_name = tblAll.constraint_name

inner join information_schema.constraint_column_usage tblFK on tblAllFK.constraint_name=tblFK.constraint_name

Thnx

October 11, 2008 Posted by patriwala | Database, SqlServer | | 5 Comments

find not working in visual studio

Find option is not working in the visual studio environment. solved this issue follow the below steps.

steps :

1) open the visual studio in safe mode using command devenv/safemode

go to command prompt and type your visual studio path. in my pc is

” C:\Program Files\Microsoft Visual Studio 8\Common7\IDE “

run above code and check.

it work then the problem either the cause should be third-party applications, services or Visual Studio Add-ins.

if find is not working yet then follow the 2nd step.

2) open the command prompt and type your visual studio path. in my pc is

” C:\Program Files\Microsoft Visual Studio 8\Common7\IDE “

type below code : devenv /resetsettings

this command is Restores Visual Studio default settings.

now check in the Visual Studio.

Thnx

September 20, 2008 Posted by patriwala | dotnet | | 2 Comments

The media set has 2 media families but only 1 are provided

I got this error when restore database from .bak file.

why this error happen?

when you backup the database at that time you have not delete the existing path means you start a back up behalf of the previous one means your backup is divided in to more parts.

steps :
1)  you select all the related .bak file.

example here mydatabase name is test1. first i backup that at that time mybackup name is test1_17.bak. second backup i take at 18 and backup file name is test1_18.bak. now when you selecte restore database at that time you selected both this file.

rightclick on database –> task –> Restore –> Database

open one dialog box — now select fromdevice and add related files (test1_17.bak and test1_18.bak).

* when you take a backup at that time you remove the previous file.

Thnx.

September 20, 2008 Posted by patriwala | Database, SqlServer | , | No Comments Yet

CS0030: Cannot convert type

Actual Error Was : CS0030 Cannot convert type ‘ASP.changepassword_aspx’ to ‘System.Web.UI.WebControls.ChangePassword’.

I have created web application using asp.net 2.0 with c#. Application Run In VS Studio Perfect but when publish this application in to local host some of the link can not run and it give this error. below is the description of that.

error

Steps :

1) open the Error Page (here is ChangePassword.aspx)

case 1 : change the PageName means Rename ChangePassword.aspx to ChPassword.aspx

case 2: change the class name in code behind and Inherit attribute of the page. here the class name is ChangePassword and Inherit attribute of page is ChangePassword. you can change both of this.

Thanx

September 14, 2008 Posted by patriwala | Asp.Net 2.0, dotnet | , | No Comments Yet

Encrypt Sections Of Web.Config File in ASP.NET 2.0

1) why the need of Encryption in Web.Config File?

We know that Web.Config file hold sensitive information like (Database server name , user name,password ect). In any database related application the database is more important.  if you do not protect database related information from malicious user or hacker sometime it create a danger situation for anyone.

below are the sections which hold the sensitive data.

1) appSettings

2) connectionStrings

3) SessionState

In dotnet Framework 2.0 introduced a protected configuration feature that allows you to encrypt sensitive data. you can configure file data using command line tool.which is describe below in detail.

There are two protected configuration providers are included.

1) RSAProtectedConfigurationProvider (default)

2) DataProtectionConfigurationProvider (Data Protection application programming interface)

  • Encrypt the connectionStrings section in Web.config

Steps :

1) create web application using (asp.net with c#).

2) Add the web.config file in your created application. add connection string in the web.config file.

   1: <connectionStrings>
   2:     <add name="mycon" connectionString="Data Source=.\sqlexpress;Initial Catalog=tempdb;uid=sa;pwd:sa007"/>
   3:   </connectionStrings>

or

   1: <connectionStrings>
   2:    <add name="mycon" connectionString="Data Source=.\sqlexpress;Initial Catalog=tempdb;Integrated Security=True"/>
   3:  </connectionStrings>

3) now here is the two possibility either you use the VS.net 2005 or Configure application as virtual Directory.

case 1 (configured application as virtual directory)

aspnet_regiis -pe “connectionStrings” -app “/Your Application Name” -prov “DataProtectionConfigurationProvider”

case 2 VS.net 2005

aspnet_regiis.exe -pef “connectionStrings” YOUR Application Path –prov “DataProtectionConfigurationProvider”

Description : aspnet_regiis.exe (%windir%\Microsoft.Net\Framework\ Dotnet Version)
Options :
1) -pe : switch specifies the configuration section to encrypt.
2) -pef : physical path for your configuration file
3) -app your web application's virtual path.
4) -prov provider name
4) run above code result will be.
  image
5) check the web.config file.
   1:    <connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
   2:      <EncryptedData>
   3:        <CipherData>
   4:          <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAjADWCXozG0u/o7BY2jzY0gQAAAACAAAAAAADZgAAqAAAABAAAADW4TyTJUuqAbIF+Hj1hlQ6AAAAAASAAACgAAAAEAAAALatNmZNNiKQeIdh/ns863VAAQAA5e6qwI4+JVZB/bL5xmHOLyewcO9pp2sc8vtcDT4ZNwK+oHDq//zsfL+cf6FDlgv++bJcXETNPl8TQ4fEqYaP8pHrim3QkFCf59B3q3tAKR9bvXvNJaUmCixcKQopPPwDH5lvmsXawT6gxNpSDqMz+4vBGN63U1oXCRn2dUpC9DxesEhgh4X5uZuCBSxjvsQM2G97mIwbFUPh8LwTSRoeiPdVz8oycnZQiO7AKpNmshpnOvjTIMQYArQyFR1IQA8DTE7qWf95Ciqapa+Kq7NInVNc/5cuYaP0+0jJBPYUw/mWpRYKD1KAUdRPpdQO6QSbVC/lK/m2Vb7OPL78M/gT07TIKTKleIjaN90wgDVaETW06o5hcSNbTZb6OudrZAw+0/uFZbxxKFQZpK5WAKl68IJzfO0YSi67EDeGPyPXCQcUAAAA26tsHR9708+5EFpzAjeFgAnHBNQ=</CipherValue>
   5:        </CipherData>
   6:      </EncryptedData>
   7:    </connectionStrings>
6) in the your page (default.aspx) put below code
Response.Write("Connection String Is " +ConfigurationManager.ConnectionStrings["mycon"].ConnectionString);
7) Run Application Check Result
image

i hope that above code is worked. now if you want to change connection string then what to do?
steps :
1)

case 1 (configured application as virtual directory)

   aspnet_regiis -pd "connectionStrings" -app "Your Application Name"

case 2 VS.net 2005

   aspnet_regiis -pdf "connectionStrings" Your Application Path
2) Result of Executed code
image
3) check the web.config file.

thnx

September 10, 2008 Posted by patriwala | Asp.Net 2.0, dotnet | | 1 Comment

Transfer Session Variable From ASP To ASP.Net 2.0

you can transfer you asp session to asp.net session. here i give small demo for that.

steps:

1) create asp page (mypage.asp)

   1:
   2: <%@LANGUAGE="Vbscript" CODEPAGE="1252"%>
   3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4: <html xmlns="http://www.w3.org/1999/xhtml">
   5: <head>
   6: <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   7: <title>Untitled Document</title>
   8: </head>
   9: <form name='form1' action='login.asp' method='post'>
  10: User Name : <input type='text' name='username'>
  11: <br>
  12: <input type='submit' value="Login">
  13: </form>
  14: <body>
  15: </body>
  16: </html>

2) create second asp page (login.asp)

   1: <%
   1:
   2: If Request.Form("username") = "" then
   3:     Response.Write("Login Failed.<br><br>")
   4: else
   5:      Response.Write("Transfer Session in To Hidden Field")
   6:     ' create asp session user here
   7:      Session("user") =Request.Form("username")
   8:      ' in the form action go to the aspx page called default.aspx
   9:      Response.Write("<form name='form1' id='form1' action='Default.aspx' method='post' >")
  10:
  11:      For each Item in Session.Contents
  12:         Response.Write("<input type=hidden name=" & Item)
  13:         Response.Write( " value=" & Session.Contents(item) & " >")
  14:      next
  15:      Response.Write("</FORM>")
  16:
  17:      Response.Write("<script>form1.submit();</script>")
  18: End If

%>

3) create aspx page with (asp.net with c#)

   1: <%@ Page Language="C#" %>
   2:
   3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4:
   5: <script runat="server">
   1:
   2:     protected void Button1_Click(object sender, EventArgs e)
   3:     {
   4:         //redirect to asp page
   5:         Response.Redirect("myasp.asp");
   6:     }
   7:     protected void Page_Load(object sender, EventArgs e)
   8:     {
   9:         //get the Request 
  10:         for (int i = 0; i < Request.Form.Count; i++)
  11:         {
  12:             //transfer value
  13:             Session[Request.Form.GetKey(i)] = Request.Form[i].ToString();
  14:         }
  15:         //check the session
  16:         if (Session["user"] != null)
  17:         {
  18:             Response.Write("Hi " + Session["user"].ToString());
  19:         }
  20:     }

</script>

   6:
   7: <html xmlns="http://www.w3.org/1999/xhtml" >
   8: <head runat="server">
   9:     <title>ASPX Page</title>
  10: </head>
  11: <body>
  12:     <form id="form1" runat="server">
  13:     <div>
  14:         <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
  15:     </form>
  16: </body>
  17: </html>

4) now start the application start page is (mypage.asp).

click on the login button it will go to login.asp page.

in the login.asp page session is create Session(”user”) =Request.Form(”username”)

if login is success then page is go to the default.asp.

on the default.aspx page load event

//get the Request

for (int i = 0; i < Request.Form.Count; i++)

{

//transfer value

Session[Request.Form.GetKey(i)] = Request.Form[i].ToString();

}

thnx

September 10, 2008 Posted by patriwala | Asp.Net 2.0, dotnet | | 1 Comment