代码之家  ›  专栏  ›  技术社区  ›  Isak Savo

如何让Silverlight从MySQL获取数据

  •  1
  • Isak Savo  · 技术社区  · 16 年前

    我在Silverlight中编写了一个小的hello world测试应用程序,我想在Linux/Apache2服务器上托管它。我希望数据来自MySQL(或其他与Linux兼容的数据库),这样我就可以将数据绑定到数据库中的内容。

    我通过使用 MySQL Connector/.NET :

    MySqlConnection conn = new MySqlConnection("Server=the.server.com;Database=theDb;User=myUser;Password=myPassword;");
    conn.Open();
    MySqlCommand command = new MySqlCommand("SELECT * FROM test;", conn);
    using (MySqlDataReader reader = command.ExecuteReader())
    {
         StringBuilder sb = new StringBuilder();
         while (reader.Read())
         {
             sb.AppendLine(reader.GetString("myColumn"));
         }
         this.txtResults.Text = sb.ToString();
    }
    

    如果我给予发布的ClickOnce应用程序完全信任(或者至少是socketPermission),并且 本地运行 .

    我想让它在服务器上运行,但无法使其正常工作,结果总是出现权限异常(不允许socketpermission)。

    如果这有任何区别,则数据库托管在与Silverlight应用程序相同的服务器上。

    编辑 好吧,我现在明白了为什么在客户端应用程序中使用DB凭据是一个坏主意(显然)。那么人们是怎么做到的呢?如何保护代理Web服务,使其以安全的方式在客户机/db之间传递数据?网上有什么例子吗?

    当然,我不是第一个想使用数据库为Silverlight应用程序供电的人吗?

    6 回复  |  直到 16 年前
        1
  •  4
  •   Rob    16 年前

        3
  •  3
  •   cruizer    16 年前

        4
  •  3
  •   angularsen Bcelik    13 年前

    Step By Step Guide to WCF RIA enabled SL4 application with Entity Framework

    <ListBox x:Name="TestList" Width="100" />
    

    public partial class Home : Page
    {
        public Home()
        {
            InitializeComponent();
    
            Loaded += Home_Loaded;
        }
    
        void Home_Loaded(object sender, RoutedEventArgs e)
        {
            var context = new FooDomainContext();
            var query = context.Load(context.GetPersonsQuery());
            TestList.ItemsSource = query.Entities;
            TestList.DisplayMemberPath = "name";
        }
    }
    

        5
  •  2
  •   Kristian J.    16 年前

        6
  •  1
  •   mjb    11 年前


    Add a new Silverlight project

    Create a new Web Service

    enter image description here

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.Services;
    
    namespace SilverlightApplication1.Web
    {
        /// <summary>
        /// Summary description for WebService1
        /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        public class WebService1 : System.Web.Services.WebService
        {
            [WebMethod]
            public string HelloWorld()
            {
                return "Hello World";
            }
        }
    }
    

    using MySql.Data.MySqlClient; 
    

    public string ExecuteScalar(string sql)
    {
        try
        {
            string result = "";
            using (MySqlConnection conn = new MySqlConnection(constr))
            {
                using (MySqlCommand cmd = new MySqlCommand())
                {
                    conn.Open();
                    cmd.Connection = conn;
                    cmd.CommandText = sql;
                    result = cmd.ExecuteScalar() + "";
                    conn.Close();
                }
            }
            return result;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    } 
    

    public string ExecuteNonQuery(string sql)
    {
        try
        {
            long i = 0;
            using (MySqlConnection conn = new MySqlConnection(constr))
            {
                using (MySqlCommand cmd = new MySqlCommand())
                {
                    conn.Open();
                    cmd.Connection = conn;
                    cmd.CommandText = sql;
                    i = cmd.ExecuteNonQuery();
                    conn.Close();
                }
            }
            return i + " row(s) affected by the last command, no resultset returned.";
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }  
    

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.Services;
    using MySql.Data.MySqlClient;
    
    namespace SilverlightApplication1.Web
    {
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        public class WebService1 : System.Web.Services.WebService
        {
            string constr = "server=localhost;user=root;pwd=1234;database=test;";
    
            [WebMethod]
            public string ExecuteScalar(string sql)
            {
                try
                {
                    string result = "";
                    using (MySqlConnection conn = new MySqlConnection(constr))
                    {
                        using (MySqlCommand cmd = new MySqlCommand())
                        {
                            conn.Open();
                            cmd.Connection = conn;
                            cmd.CommandText = sql;
                            result = cmd.ExecuteScalar() + "";
                            conn.Close();
                        }
                    }
                    return result;
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
    
            [WebMethod]
            public string ExecuteNonQuery(string sql)
            {
                try
                {
                    long i = 0;
                    using (MySqlConnection conn = new MySqlConnection(constr))
                    {
                        using (MySqlCommand cmd = new MySqlCommand())
                        {
                            conn.Open();
                            cmd.Connection = conn;
                            cmd.CommandText = sql;
                            i = cmd.ExecuteNonQuery();
                            conn.Close();
                        }
                    }
                    return i + " row(s) affected by the last command, no resultset returned.";
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }  
        }
    } 
    

    Rebuild the project

    http://www.mywebsite.com/clientaccesspolicy.xml http://www.mywebsite.com/crossdomain.xml

    <?xml version="1.0" encoding="utf-8"?>
    <access-policy>
      <cross-domain-access>
        <policy>
          <allow-from http-request-headers="SOAPAction">
            <domain uri="*"/>
          </allow-from>
          <grant-to>
            <resource path="/" include-subpaths="true"/>
          </grant-to>
        </policy>
      </cross-domain-access>
    </access-policy>
    

    <?xml version="1.0" encoding="utf-8"?>
    <access-policy>
      <cross-domain-access>
        <policy>
          <allow-from http-request-headers="SOAPAction">
            <domain uri="http://www.myanotherwebsite.com"/>
          </allow-from>
          <grant-to>
            <resource path="/" include-subpaths="true"/>
          </grant-to>
        </policy>
      </cross-domain-access>
    </access-policy>
    

    <?xml version="1.0" encoding="utf-8" ?>
    <!DOCTYPE cross-domain-policy SYSTEM 
    "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
    <cross-domain-policy>
      <allow-http-request-headers-from domain="*" headers="SOAPAction,Content-Type"/>
    </cross-domain-policy>
    

    Making a Service Available Across Domain Boundaries (MSDN)


    Add a Service Reference to Silverlight

    http://www.mywebsite.com/MyCoolWebService.asmx

    Web Service Browser

    View in Object Browser

    Object of WebService1SoapClient

    Design a simple SilverLight App

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    
    namespace SilverlightApplication1
    {
        public partial class MainPage : UserControl
        {
            public MainPage()
            {
                InitializeComponent();
            }
    
            private void btExecuteScalar_Click(object sender, RoutedEventArgs e)
            {
            }
    
            private void btExecuteNonQuery_Click(object sender, RoutedEventArgs e)
            {
            }
        }
    }
    


    public partial class MainPage : UserControl
    {
        ServiceReference1.WebService1SoapClient myService;
    
        public MainPage()
        {
            InitializeComponent();
            myService = new ServiceReference1.WebService1SoapClient();
            myService.ExecuteScalarCompleted += myService_ExecuteScalarCompleted;
            myService.ExecuteNonQueryCompleted += myService_ExecuteNonQueryCompleted;
        }
    
        void myService_ExecuteNonQueryCompleted(object sender, 
                       ServiceReference1.ExecuteNonQueryCompletedEventArgs e)
        {
            MessageBox.Show(e.Result);
        }
    
        void myService_ExecuteScalarCompleted(object sender, 
             ServiceReference1.ExecuteScalarCompletedEventArgs e)
        {
            MessageBox.Show(e.Result);
        }
    
        private void btExecuteScalar_Click(object sender, RoutedEventArgs e)
        {
            myService.ExecuteScalarAsync(textBox1.Text);
        }
    
        private void btExecuteNonQuery_Click(object sender, RoutedEventArgs e)
        {
            myService.ExecuteNonQueryAsync(textBox1.Text);
        }
    }
    

    Testing

    Testing

    Testing

    update the Service Reference

    1. Original Post - Connecting MySQL From SilverLight With Web Services - CodeProject.com (written by me)
    2. Access a Web Service from a Silverlight Application
    3. HOW TO: Write a Simple Web Service by Using Visual C# .NET
    4. How to: Build a Service for Silverlight Clients