Windows Phone calls the weather forecast program implementation code

Source: Internet
Author: User
Windows Phone's local Database SQL Server CE is a new feature of Mango update in version 7.1. Therefore, you must use Windows Phone 7.1 APIs to use the SQL Server CE database in applications. This database uses Linq to perform query and other operations.
We now use databases to store city data, including the province, city name, and city code. In the program, we only perform simple inserts and queries. For detailed database operations, see
Http://windowsphonegeek.com/tips/Windows-Phone-Mango-Local-Database (SQL-CE)-Introduction or MSDN.
Now, go back to the project and create a data table, CityInfoTable.
Right-click the project and choose Add -- class. Name CityInfoTable. cs and add reference. Project ---- right-click --- add reference.
Find System. Data. Linq. And click OK.

Then add the namespace in CityInfoTable. cs.

The code is as follows: Copy code
Using System. Data. Linq. Mapping;
Using System. ComponentModel;

 

Then define the primary key and other attributes in the CItyInfoTable data table, and provide the complete CityInfoTable. cs code.

 

The code is as follows: Copy code

Using System;
Using System. Net;
Using System. Windows;
Using System. Windows. Controls;
Using System. Windows. Documents;
Using System. Windows. Ink;
Using System. Windows. Input;
Using System. Windows. Media;
Using System. Windows. Media. Animation;
Using System. Windows. Shapes;
Using System. Data. Linq. Mapping;
Using System. ComponentModel;


Namespace WeatherForecast
{
[Table] // define CItyInfoTable as a Table
Public class CityInfoTable
    {
// Define the table's auto-increment ID. Set as primary key
Private int _ cityInfoid;

// Column: defines a member as a table field. If not, this member is not a field.
[Column (IsPrimaryKey = true, IsDbGenerated = true,
DbType = "int not null Identity", CanBeNull = false, AutoSync = AutoSync. OnInsert)]
Public int CityInfoid
        {
Get
            {
Return _ cityInfoid;
            }
Set
            {
_ CityInfoid = value;
            }
        }


// Define the province name:
Private string _ province;
[Column]
Public string Province
        {
Get
            {
Return _ province;
            }
Set
            {
_ Province = value;
            }
        }

// Define the city name
Private string _ cityName;

[Column]
Public string CityName
        {
Get
            {
Return _ cityName;
            }
Set
            {
_ CityName = value;
            }
        }

// Define the city code
Private string _ cityCode;

[Column]
Public string CityCode
        {
Get
            {
Return _ cityCode;
            }
Set
            {
_ CityCode = value;
            }
        }

    }
}

Now define another database. Project --- right-click --- New Class, and name it CityDataContext. cs.

Add a namespace.

Using System. Data. Linq;
Then let this class inherit from DataContext.

The complete code of CityDataContext. cs is provided:

 

The code is as follows: Copy code

Using System;
Using System. Net;
Using System. Windows;
Using System. Windows. Controls;
Using System. Windows. Documents;
Using System. Windows. Ink;
Using System. Windows. Input;
Using System. Windows. Media;
Using System. Windows. Media. Animation;
Using System. Windows. Shapes;
Using System. Data. Linq;


Namespace WeatherForecast
{
/// <Summary>
/// Define a database
/// </Summary>
Public class CityDataContext: DataContext
    {
// Define the database connection string
Public static string connectionString = "Data Source = isostore:/CityInfo. sdf ";

/// Pass the database connection string to the DataContext base class
Public CityDataContext (string connectionString): base (connectionString ){}


// Define a data table. If multiple data tables exist, you can add them as member variables.
Public Table <CityInfoTable> CityInfos
        {
Get
            {
Return this. GetTable <CityInfoTable> ();
            }
        }
    }
}
 

By now, the database has been written. The novice will certainly have questions and will not see any databases. No SDF files are displayed in the project.

Because we need to use code to create a database when building a program. We can see from the connection string above. After the database is created, it is placed in Isolatedstorage and this is created in App. the launch events in xaml are implemented.

You can add such code to this event to create a database:

 

The code is as follows: Copy code

Using (CityDataContext db = new CityDataContext (CityDataContext. connectionString ))
            {

If (db. DatabaseExists () = false)
                {

// Create a database

Db. CreateDatabase ();
}
}

We will not do this for the moment. Add an XML file for city information. Download: http://115.com/file/anme1scg#citycode.xml

Copy this file. Right-click and paste the project. Add the citycode. xml file to the project.

Next, perform XML parsing. The XDocument class. Here is a simple application.

We need to add code to the Launching event in App. xaml. Because we need to create a database when running the program for the first time, and parse the citycode. xml data to add it to the database.

To read files from the project. Application. GetResourceStream. This function can only read resource files. Change the Building attribute of the citycode. xml file to Resource.

Operation method: Select citycode. xml ----- Click properties --- generate operation (Building) to change to Resource.

To use the XDocument class, you must add references. Add System. Xml. Linq. You have added many references, so I will not detail how to perform this operation.

Add a namespace in App. xaml. cs;

The code is as follows: Copy code

 
Using System. Windows. Resources;
Using System. IO;
Using System. Xml. Linq;

Add member functions:

 

The code is as follows: Copy code

Private void CreatDB ()
        {
Using (CityDataContext db = new CityDataContext (CityDataContext. connectionString ))
            {

If (db. DatabaseExists () = false)
                {

// Create a database

Db. CreateDatabase ();
// Read the resource file. The file is in XML format. The Building attribute of this file is Resource.
StreamResourceInfo sri = Application. GetResourceStream (new Uri ("/WeatherForecast; component/citycode. xml ",
UriKind. Relative ));
// Read the data and save it to the result of the String type.
String result;
Using (StreamReader sr = new StreamReader (sri. Stream ))
                    {
Result = sr. ReadToEnd ();
                    }

// Use the XDocument class to parse data
XDocument doc = XDocument. Parse (result );

// Parse the data and store it in the database
Foreach (XElement item in doc. Descendants ("root"). Nodes ())
                    {
// You can know the data in the file. The data we need is on these two nodes. Descendants is used to find subnodes.
String province = item. Attribute ("data"). Value;
Foreach (XElement itemnode in item. Descendants ("city "))
                        {
String cityname = itemnode. Element ("cityname"). Value;
String cityid = itemnode. Element ("cityid"). Value;
// Store data into the database
CityInfoTable cityInfo = new CityInfoTable ();
CityInfo. CityCode = cityid;
CityInfo. Province = province;
CityInfo. CityName = cityname;
Db. CityInfos. InsertOnSubmit (cityInfo );
                        }
                    }
// Submit the database for updates
Db. SubmitChanges ();
                }

            }
        }
 

Add the following code to the Launching event:

CreatDB ();
In this way, we can create a database when executing the program for the first time, parse the XML data, and store the city information into the database.

So let's test it.

Test in the Loaded event of MainPage to query the data in Beijing. A pop-up window is displayed.

Add the following code to the Loaded event:

The code is as follows: Copy code

Using (CityDataContext db = new CityDataContext (CityDataContext. connectionString ))
            {
IQueryable <CityInfoTable> queries =
From c in db. CityInfos where c. Province = "Beijing" & c. CityName = "Beijing" select c;
MessageBox. Show (queries. First (). CityName + queries. First (). CityCode );
            }


Successful! Comment out the added test code...

PS: I am quite confused when I debug the database and parse XML. Do not make mistakes. Do not make mistakes...

If an error occurs, the database is created. However, data is not included. To delete a database, restart the simulator. Because the data in the IsolatedStorage simulator is no longer restarted. However, if my computer restarts the simulator, it won't take five to six minutes .. Multiple errors, several times, and half an hour.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.