Search Results

Search found 38 results on 2 pages for 'applicationsettings'.

Page 1/2 | 1 2  | Next Page >

  • Asp.net Webdeployment Project override applicationSettings

    - by citronas
    I got a web deyploment project for a web application project in vs 2008. While building the web deployment project, I want to replace properties in the web.config. My settings are autogenrated by the deisgner. <applicationSettings> <NAMESPACE.Properties.Settings> <setting name="Testenvironment" serializeAs="String"> <value>True</value> </setting> </NAMESPACE.Properties.Settings> </applicationSettings> In the config file which contains the settings for the specific server looks like the following: <?xml version="1.0"?> <applicationSettings> <NAMESPACE.Properties.Settings> <setting name="Testenvironment" serializeAs="String"> <value>False</value> </setting> </NAMESPACE.Properties.Settings> </applicationSettings> Sadly, this does not work. I get an error "The format of a configSource file must be an element containing the name of the section" that highlights the second line (2nd example code). How must the Tag be named in order to make evertything work? Edit: Deleting the "applicationSetting"-Tags does not work either.

    Read the article

  • applicationSettings and Web.config

    - by Eric J.
    I have a DLL that provides logging that I use for WebForms projects and now wish to use it in an ASP.Net MVC 2 project. Some aspects of that DLL are configured in app.config: <configuration> <configSections> <section name="Tools.Instrumentation.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </sectionGroup> </configSections> <applicationSettings> <Tools.Instrumentation.Properties.Settings> <setting name="LogLevel" serializeAs="String"> <value>DEBUG</value> </setting> <setting name="AppName" serializeAs="String"> <value>MyApp</value> </setting> <setting name="Port" serializeAs="String"> <!--value>33333</value--> <value>0</value> </setting> </Tools.Instrumentation.Properties.Settings> </configuration> However, when I create a similar entry in Web.config, I get the error: Unrecognized configuration section applicationSettings My two-part question: How do I make this config entry work in Web.config? Where can I read up on the conceptual differences between WinForms configuration and ASP.Net configuration?

    Read the article

  • Using of ApplicationSettings in markup code

    - by Dirk
    I want to use ApplicationSettings in the markup code of an ASP.NET Web Application. Inspired by code behind this was my first try: <%= My.Settings.MyApplicationSetting %> No success. I ended up with this lengthy statement <%= Global.MyRootNameSpace.My.MySettings.Default.MyApplicationSetting %> I can’t believe that this is the best solution. Isn’t it?

    Read the article

  • Property being immediately reset by ApplicationSetting Property Binding

    - by Slider345
    I have a .net 2.0 windows application written in c#, which currently uses several project settings to store user configurations. The forms in the application are made up of lots of user controls, each of which have properties that need to be set to these project settings. Right now these settings are manually assigned to the user control properties. I was hoping to simplify the code by replacing the manual implementation with ApplicationSettings Property Bindings. However, my first property is not behaving properly at all. The setting is an integer, used to record a port number typed into a text box. The setting is bound to an integer property on a user control, and that property sets the Text property on a TextBox control. When I type a new value into the textbox at runtime, as soon as the textbox loses focus, it is immediately replaced by the original value. A breakpoint on the property shows that it is immediately setting the property to the setting from the properties collection after I set it. Can anyone see what I'm doing wrong? Here's some code: The setting: [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("1000")] public int Port { get{ return ((int)(this["Port"])); } set{ this["Port"] = value; } } The binding: this.ctrlNetworkConfig.DataBindings.Add(new System.Windows.Forms.Binding("PortNumber", global::TestProject.Properties.Settings.Default, "Port", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.ctrlNetworkConfig.PortNumber = global::TestProject.Properties.Settings.Default.Port; And lastly, the property on the user control: public int PortNumber { get{ int port; if(int.TryParse(this.txtPortNumber.Text, out port)) return port; else return 0; } set{ txtPortNumber.Text = value.ToString(); } } Any thoughts? Thanks in advance for your help. EDIT: Sorry about the formatting, trying to correct.

    Read the article

  • Validating Application Settings Key Values in Isolated Storage for Windows Phone Applications

    - by Martin Anderson
    Hello everyone. I am very new at all this c# Windows Phone programming, so this is most probably a dumb question, but I need to know anywho... IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings; if (!appSettings.Contains("isFirstRun")) { firstrunCheckBox.Opacity = 0.5; MessageBox.Show("isFirstRun not found - creating as true"); appSettings.Add("isFirstRun", "true"); appSettings.Save(); firstrunCheckBox.Opacity = 1; firstrunCheckBox.IsChecked = true; } else { if (appSettings["isFirstRun"] == "true") { firstrunCheckBox.Opacity = 1; firstrunCheckBox.IsChecked = true; } else if (appSettings["isFirstRun"] == "false") { firstrunCheckBox.Opacity = 1; firstrunCheckBox.IsChecked = false; } else { firstrunCheckBox.Opacity = 0.5; } } I am trying to firstly check if there is a specific key in my Application Settings Isolated Storage, and then wish to make a CheckBox appear checked or unchecked depending on if the value for that key is "true" or "false". Also I am defaulting the opacity of the checkbox to 0.5 opacity when no action is taken upon it. With the code I have, I get the warnings Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string' Can someone tell me what I am doing wrong. I have explored storing data in an Isolated Storage txt file, and that worked, I am now trying Application Settings, and will finally try to download and store an xml file, as well as create and store user settings into an xml file. I want to try understand all the options open to me, and use which ever runs better and quicker

    Read the article

  • VisualStudio 2010 Settings Page - Collection Settings

    - by Ed Eichman
    I have a list of Filemaker database names Each DB name has a list of field/attribute pairs associated with it I have a windows form application in C# 4.0 (vs2010) that wants to use the above data I would like to maintain the list either in the Visual Studio settings page, or in one of the standard visual studio settings files using the standard .NET settings calls I would like to avoid writing my own custom settings, xml, xds (to avoid the "Could not find schema information for the element/attribute " errors) I just have a slightly complicated INI file! I don't want to complicate my life! Do any easy solutions exist? Unless someone has a brighter idea, I am simply going to write string settings with names that indicate it's a FM DB (e.g. "fmdbAddresses"), and values that concat my field/attribute pairs (e.g. "gUserResult=skipField|gAddressID=convertToInt|gAddressID=uniqueIx")

    Read the article

  • how to change .NET user settings location

    - by mack369
    By default settings are stored at: C:\Documents and Settings\\Local Settings\Application Data\<Project Name> How can I change this path to application directory. I also don't want to have different files for different users. How make the settings global? I tried to change the scope of the settings to "application" but then I cannot change them at runtime.

    Read the article

  • How use applicationSettings in the new web.config configuration in VS2010?

    - by citronas
    I'm used to use web deployment projects. Currently I am developing a new web application with VS2010 and want to try to get along with the new web.config principle and deployment issues. How can I replace a simple setting like <applicationSettings> <NAMESPACE> <setting name="Testenvironment" serializeAs="String"> <value>True</value> </setting> </NAMESPACE> </applicationSettings> I want to have this setting to be set to True in Debug, and false in Release. How must the entries in the Web.Debug.config and Web.Release.Config look like? And by the way: Is there some documentation about the new web.config issue? Can't seem to google for the correct keywords.

    Read the article

  • Why does a simple ApplicationSetting PropertyBinding for a Form does not work in C#?

    - by Mike Rosenblum
    My question involves this simple walkthrough shown in the article Preserve Size and Location of Windows Forms – Part I by Dennis Wallentin. This approach works 100% fine when using VB.NET. When using the same steps in C#, however, the settings within the Settings tab of the application's properties looks correct, and the app.config file looks right, but the values are not saved when you run it. The app.config file winds up looking like this: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" > <section name="WindowsAppCs.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /> </sectionGroup> </configSections> <userSettings> <WindowsAppCs.Properties.Settings> <setting name="Location" serializeAs="String"> <value>0, 0</value> </setting> <setting name="Size" serializeAs="String"> <value>284, 262</value> </setting> </WindowsAppCs.Properties.Settings> </userSettings> </configuration> It looks right to me, but the values do not update when running hosted within Visual Studio or when running the compiled EXE. I am sure that something very simple needs to be added or done, but I don't know what. Does anyone have any ideas here? Much thanks in advance...

    Read the article

  • How do I access the ApplicationSettings section from another assembly?

    - by Calanus
    I have a dll that is referenced by the parent (executing) assembly. In the ApplicationSettings section of the app.config for the parent assembly I have some settings that can be accessed in the normal intellisense manner (e.g. Properties.Settings.Default.SMTPServer). How do I access these settings from the referenced dll? I obviously can't use intellisense as they are not in the same assembly!

    Read the article

  • FormatException with IsolatedStorageSettings

    - by Jurgen Camilleri
    I have a problem when serializing a Dictionary<string,Person> to IsolatedStorageSettings. I'm doing the following: public Dictionary<string, Person> Names = new Dictionary<string, Person>(); if (!IsolatedStorageSettings.ApplicationSettings.Contains("Names")) { //Add to dictionary Names.Add("key", new Person(false, new System.Device.Location.GeoCoordinate(0, 0), new List<GeoCoordinate>() { new GeoCoordinate(35.8974, 14.5099), new GeoCoordinate(35.8974, 14.5099), new GeoCoordinate(35.8973, 14.5100), new GeoCoordinate(35.8973, 14.5099) })); //Serialize dictionary to IsolatedStorage IsolatedStorageSettings.ApplicationSettings.Add("Names", Names); IsolatedStorageSettings.ApplicationSettings.Save(); } Here is my Person class: [DataContract] public class Person { [DataMember] public bool Unlocked { get; set; } [DataMember] public GeoCoordinate Location { get; set; } [DataMember] public List<GeoCoordinate> Bounds { get; set; } public Person(bool unlocked, GeoCoordinate location, List<GeoCoordinate> bounds) { this.Unlocked = unlocked; this.Location = location; this.Bounds = bounds; } } The code works the first time, however on the second run I get a System.FormatException at the if condition. Any help would be highly appreciated thanks. P.S.: I tried an IsolatedStorageSettings.ApplicationSettings.Clear() but the call to Clear also gives a FormatException. I have found something new...the exception occurs twenty-five times, or at least that's how many times it shows up in the Output window. However after that, the data is deserialized perfectly. Should I be worried about the exceptions if they do not stop the execution of the program? EDIT: Here's the call stack when the exception occurs: mscorlib.dll!double.Parse(string s, System.Globalization.NumberStyles style, System.IFormatProvider provider) + 0x17 bytes System.Xml.dll!System.Xml.XmlConvert.ToDouble(string s) + 0x4b bytes System.Xml.dll!System.Xml.XmlReader.ReadContentAsDouble() + 0x1f bytes System.Runtime.Serialization.dll!System.Xml.XmlDictionaryReader.XmlWrappedReader.ReadContentAsDouble() + 0xb bytes System.Runtime.Serialization.dll!System.Xml.XmlDictionaryReader.ReadElementContentAsDouble() + 0x35 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlReaderDelegator.ReadElementContentAsDouble() + 0x19 bytes mscorlib.dll!System.Reflection.RuntimeMethodInfo.InternalInvoke(System.Reflection.RuntimeMethodInfo rtmi, object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object parameters, System.Globalization.CultureInfo culture, bool isBinderDefault, System.Reflection.Assembly caller, bool verifyAccess, ref System.Threading.StackCrawlMark stackMark) mscorlib.dll!System.Reflection.RuntimeMethodInfo.InternalInvoke(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture, ref System.Threading.StackCrawlMark stackMark) + 0x168 bytes mscorlib.dll!System.Reflection.MethodBase.Invoke(object obj, object[] parameters) + 0xa bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlFormatReader.ReadValue(System.Type type, string name, string ns, System.Runtime.Serialization.XmlObjectSerializerReadContext context, System.Runtime.Serialization.XmlReaderDelegator xmlReader) + 0x138 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlFormatReader.ReadMemberAtMemberIndex(System.Runtime.Serialization.ClassDataContract classContract, ref object objectLocal, System.Runtime.Serialization.DeserializedObject desObj) + 0xc4 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlFormatReader.ReadClass(System.Runtime.Serialization.DeserializedObject desObj, System.Runtime.Serialization.ClassDataContract classContract, int membersRead) + 0xf3 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlFormatReader.Deserialize(System.Runtime.Serialization.XmlObjectSerializerReadContext context) + 0x36 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlFormatReader.InitializeCallStack(System.Runtime.Serialization.DataContract clContract, System.Runtime.Serialization.XmlReaderDelegator xmlReaderDelegator, System.Runtime.Serialization.XmlObjectSerializerReadContext xmlObjContext, System.Xml.XmlDictionaryString[] memberNamesColl, System.Xml.XmlDictionaryString[] memberNamespacesColl) + 0x77 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.CollectionDataContract.ReadXmlValue(System.Runtime.Serialization.XmlReaderDelegator xmlReader, System.Runtime.Serialization.XmlObjectSerializerReadContext context) + 0x5d bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(System.Runtime.Serialization.DataContract dataContract, System.Runtime.Serialization.XmlReaderDelegator reader) + 0x3 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(System.Runtime.Serialization.XmlReaderDelegator reader, string name, string ns, ref System.Runtime.Serialization.DataContract dataContract) + 0x10e bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(System.Runtime.Serialization.XmlReaderDelegator xmlReader, System.Type declaredType, System.Runtime.Serialization.DataContract dataContract, string name, string ns) + 0xb bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.DataContractSerializer.InternalReadObject(System.Runtime.Serialization.XmlReaderDelegator xmlReader, bool verifyObjectName) + 0x124 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(System.Runtime.Serialization.XmlReaderDelegator reader, bool verifyObjectName) + 0xe bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlObjectSerializer.ReadObject(System.Xml.XmlDictionaryReader reader) + 0x7 bytes System.Runtime.Serialization.dll!System.Runtime.Serialization.XmlObjectSerializer.ReadObject(System.IO.Stream stream) + 0x17 bytes System.Windows.dll!System.IO.IsolatedStorage.IsolatedStorageSettings.Reload() + 0xa3 bytes System.Windows.dll!System.IO.IsolatedStorage.IsolatedStorageSettings.IsolatedStorageSettings(bool useSiteSettings) + 0x20 bytes System.Windows.dll!System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.get() + 0xd bytes

    Read the article

  • Change dynamic web reference from web./app.config

    - by Snæbjørn
    I have a problem changing a dynamic web reference in the config file. Changing the url in the config file doesn't have any effect. I have to change the url in .settings and compile for it to change. I added the web reference using the wizard. Set the URL behavior to dynamic, which added the relevant XML tags in config file. In my solution I have the web API (web reference) in a separate project (class lib), so I referenced the project and copied the <applicationSettings> over. <applicationSettings> <StartupProject.Properties.Settings> <setting name="WebReference" serializeAs="String"> <value>http://someurl/somefile.asmx</value> </setting> </StartupProject.Properties.Settings> </applicationSettings> Note that it's <StartupProject.Properties.Settings> and not <WebRefProject.Properties.Settings>. Are there some limitations I'm not aware of or am I doing something wrong?

    Read the article

  • Configuring Application/User Settings in WPF the easy way.

    - by mbcrump
    In this tutorial, we are going to configure the application/user settings in a WPF application the easy way. Most example that I’ve seen on the net involve the ConfigurationManager class and involve creating your own XML file from scratch. I am going to show you a easier way to do it. (in my humble opinion) First, the definitions: User Setting – is designed to be something specific to the user. For example, one user may have a requirement to see certain stocks, news articles or local weather. This can be set at run-time. Application Setting – is designed to store information such as a database connection string. These settings are read-only at run-time. 1) Lets create a new WPF Project and play with a few settings. Once you are inside VS, then paste the following code snippet inside the <Grid> tags. <Grid> <TextBox Height="23" HorizontalAlignment="Left" Margin="12,11,0,0" Name="textBox1" VerticalAlignment="Top" Width="285" Grid.ColumnSpan="2" /> <Button Content="Set Title" Name="button2" Click="button2_Click" Margin="108,40,96,114" /> <TextBlock Height="23" Name="textBlock1" Text="TextBlock" VerticalAlignment="Bottom" Width="377" /> </Grid> Basically, its just a Textbox, Button and TextBlock. The main Window should look like the following:   2) Now we are going to setup our Configuration Settings. Look in the Solution Explorer and double click on the Settings.settings file. Make sure that your settings file looks just like mine included below:   What just happened was the designer created an XML file and created the Settings.Designer.cs file which looks like this: //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WPFExam.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("ApplicationName")] public string ApplicationName { get { return ((string)(this["ApplicationName"])); } set { this["ApplicationName"] = value; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("SQL_SRV342")] public string DatabaseServerName { get { return ((string)(this["DatabaseServerName"])); } } } } The XML File is named app.config and looks like this: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" > <section name="WPFExam.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /> </sectionGroup> <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" > <section name="WPFExam.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </sectionGroup> </configSections> <userSettings> <WPFExam.Properties.Settings> <setting name="ApplicationName" serializeAs="String"> <value>ApplicationName</value> </setting> </WPFExam.Properties.Settings> </userSettings> <applicationSettings> <WPFExam.Properties.Settings> <setting name="DatabaseServerName" serializeAs="String"> <value>SQL_SRV342</value> </setting> </WPFExam.Properties.Settings> </applicationSettings> </configuration> 3) The only left now is the code behind the button. Double click the button and replace the MainWindow() method with the following code snippet. public MainWindow() { InitializeComponent(); this.Title = Properties.Settings.Default.ApplicationName; textBox1.Text = Properties.Settings.Default.ApplicationName; textBlock1.Text = Properties.Settings.Default.DatabaseServerName; } private void button2_Click(object sender, RoutedEventArgs e) { Properties.Settings.Default.ApplicationName = textBox1.Text.ToString(); Properties.Settings.Default.Save(); } Run the application and type something in the textbox and hit the Set Title button. Now, restart the application and you should see the text that you entered earlier.   If you look at the button2 click event, you will see that it was actually 2 lines of codes to save to the configuration file. I hope this helps, for more information consult MSDN.

    Read the article

  • Get XML from Server for Use on Windows Phone

    - by psheriff
    When working with mobile devices you always need to take into account bandwidth usage and power consumption. If you are constantly connecting to a server to retrieve data for an input screen, then you might think about moving some of that data down to the phone and cache the data on the phone. An example would be a static list of US State Codes that you are asking the user to select from. Since this is data that does not change very often, this is one set of data that would be great to cache on the phone. Since the Windows Phone does not have an embedded database, you can just use an XML string stored in Isolated Storage. Of course, then you need to figure out how to get data down to the phone. You can either ship it with the application, or connect and retrieve the data from your server one time and thereafter cache it and retrieve it from the cache. In this blog post you will see how to create a WCF service to retrieve data from a Product table in a database and send that data as XML to the phone and store it in Isolated Storage. You will then read that data from Isolated Storage using LINQ to XML and display it in a ListBox. Step 1: Create a Windows Phone Application The first step is to create a Windows Phone application called WP_GetXmlFromDataSet (or whatever you want to call it). On the MainPage.xaml add the following XAML within the “ContentPanel” grid: <StackPanel>  <Button Name="btnGetXml"          Content="Get XML"          Click="btnGetXml_Click" />  <Button Name="btnRead"          Content="Read XML"          IsEnabled="False"          Click="btnRead_Click" />  <ListBox Name="lstData"            Height="430"            ItemsSource="{Binding}"            DisplayMemberPath="ProductName" /></StackPanel> Now it is time to create the WCF Service Application that you will call to get the XML from a table in a SQL Server database. Step 2: Create a WCF Service Application Add a new project to your solution called WP_GetXmlFromDataSet.Services. Delete the IService1.* and Service1.* files and the App_Data folder, as you don’t generally need these items. Add a new WCF Service class called ProductService. In the IProductService class modify the void DoWork() method with the following code: [OperationContract]string GetProductXml(); Open the code behind in the ProductService.svc and create the GetProductXml() method. This method (shown below) will connect up to a database and retrieve data from a Product table. public string GetProductXml(){  string ret = string.Empty;  string sql = string.Empty;  SqlDataAdapter da;  DataSet ds = new DataSet();   sql = "SELECT ProductId, ProductName,";  sql += " IntroductionDate, Price";  sql += " FROM Product";   da = new SqlDataAdapter(sql,    ConfigurationManager.ConnectionStrings["Sandbox"].ConnectionString);   da.Fill(ds);   // Create Attribute based XML  foreach (DataColumn col in ds.Tables[0].Columns)  {    col.ColumnMapping = MappingType.Attribute;  }   ds.DataSetName = "Products";  ds.Tables[0].TableName = "Product";  ret = ds.GetXml();   return ret;} After retrieving the data from the Product table using a DataSet, you will want to set each column’s ColumnMapping property to Attribute. Using attribute based XML will make the data transferred across the wire a little smaller. You then set the DataSetName property to the top-level element name you want to assign to the XML. You then set the TableName property on the DataTable to the name you want each element to be in your XML. The last thing you need to do is to call the GetXml() method on the DataSet object which will return an XML string of the data in your DataSet object. This is the value that you will return from the service call. The XML that is returned from the above call looks like the following: <Products>  <Product ProductId="1"           ProductName="PDSA .NET Productivity Framework"           IntroductionDate="9/3/2010"           Price="5000" />  <Product ProductId="3"           ProductName="Haystack Code Generator for .NET"           IntroductionDate="7/1/2010"           Price="599.00" />  ...  ...  ... </Products> The GetProductXml() method uses a connection string from the Web.Config file, so add a <connectionStrings> element to the Web.Config file in your WCF Service application. Modify the settings shown below as needed for your server and database name. <connectionStrings>  <add name="Sandbox"        connectionString="Server=Localhost;Database=Sandbox;                         Integrated Security=Yes"/></connectionStrings> The Product Table You will need a Product table that you can read data from. I used the following structure for my product table. Add any data you want to this table after you create it in your database. CREATE TABLE Product(  ProductId int PRIMARY KEY IDENTITY(1,1) NOT NULL,  ProductName varchar(50) NOT NULL,  IntroductionDate datetime NULL,  Price money NULL) Step 3: Connect to WCF Service from Windows Phone Application Back in your Windows Phone application you will now need to add a Service Reference to the WCF Service application you just created. Right-mouse click on the Windows Phone Project and choose Add Service Reference… from the context menu. Click on the Discover button. In the Namespace text box enter “ProductServiceRefrence”, then click the OK button. If you entered everything correctly, Visual Studio will generate some code that allows you to connect to your Product service. On the MainPage.xaml designer window double click on the Get XML button to generate the Click event procedure for this button. In the Click event procedure make a call to a GetXmlFromServer() method. This method will also need a “Completed” event procedure to be written since all communication with a WCF Service from Windows Phone must be asynchronous.  Write these two methods as follows: private const string KEY_NAME = "ProductData"; private void GetXmlFromServer(){  ProductServiceClient client = new ProductServiceClient();   client.GetProductXmlCompleted += new     EventHandler<GetProductXmlCompletedEventArgs>      (client_GetProductXmlCompleted);   client.GetProductXmlAsync();  client.CloseAsync();} void client_GetProductXmlCompleted(object sender,                                   GetProductXmlCompletedEventArgs e){  // Store XML data in Isolated Storage  IsolatedStorageSettings.ApplicationSettings[KEY_NAME] = e.Result;   btnRead.IsEnabled = true;} As you can see, this is a fairly standard call to a WCF Service. In the Completed event you get the Result from the event argument, which is the XML, and store it into Isolated Storage using the IsolatedStorageSettings.ApplicationSettings class. Notice the constant that I added to specify the name of the key. You will use this constant later to read the data from Isolated Storage. Step 4: Create a Product Class Even though you stored XML data into Isolated Storage when you read that data out you will want to convert each element in the XML file into an actual Product object. This means that you need to create a Product class in your Windows Phone application. Add a Product class to your project that looks like the code below: public class Product{  public string ProductName{ get; set; }  public int ProductId{ get; set; }  public DateTime IntroductionDate{ get; set; }  public decimal Price{ get; set; }} Step 5: Read Settings from Isolated Storage Now that you have the XML data stored in Isolated Storage, it is time to use it. Go back to the MainPage.xaml design view and double click on the Read XML button to generate the Click event procedure. From the Click event procedure call a method named ReadProductXml().Create this method as shown below: private void ReadProductXml(){  XElement xElem = null;   if (IsolatedStorageSettings.ApplicationSettings.Contains(KEY_NAME))  {    xElem = XElement.Parse(     IsolatedStorageSettings.ApplicationSettings[KEY_NAME].ToString());     // Create a list of Product objects    var products =         from prod in xElem.Descendants("Product")        orderby prod.Attribute("ProductName").Value        select new Product        {          ProductId = Convert.ToInt32(prod.Attribute("ProductId").Value),          ProductName = prod.Attribute("ProductName").Value,          IntroductionDate =             Convert.ToDateTime(prod.Attribute("IntroductionDate").Value),          Price = Convert.ToDecimal(prod.Attribute("Price").Value)        };     lstData.DataContext = products;  }} The ReadProductXml() method checks to make sure that the key name that you saved your XML as exists in Isolated Storage prior to trying to open it. If the key name exists, then you retrieve the value as a string. Use the XElement’s Parse method to convert the XML string to a XElement object. LINQ to XML is used to iterate over each element in the XElement object and create a new Product object from each attribute in your XML file. The LINQ to XML code also orders the XML data by the ProductName. After the LINQ to XML code runs you end up with an IEnumerable collection of Product objects in the variable named “products”. You assign this collection of product data to the DataContext of the ListBox you created in XAML. The DisplayMemberPath property of the ListBox is set to “ProductName” so it will now display the product name for each row in your products collection. Summary In this article you learned how to retrieve an XML string from a table in a database, return that string across a WCF Service and store it into Isolated Storage on your Windows Phone. You then used LINQ to XML to create a collection of Product objects from the data stored and display that data in a Windows Phone list box. This same technique can be used in Silverlight or WPF applications too. NOTE: You can download the complete sample code at my website. http://www.pdsa.com/downloads. Choose Tips & Tricks, then "Get XML From Server for Use on Windows Phone" from the drop-down. Good Luck with your Coding,Paul Sheriff ** SPECIAL OFFER FOR MY BLOG READERS **Visit http://www.pdsa.com/Event/Blog for a free video on Silverlight entitled Silverlight XAML for the Complete Novice - Part 1.  

    Read the article

  • MSBuild Community Tasks can't see msbuild in cmd

    - by phenevo
    Hi, I have winforms project app.config: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" > <section name="MyClient.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </sectionGroup> </configSections> <applicationSettings> <MyClient.Properties.Settings> <setting name="MyClient_MyService_MyService" serializeAs="String"> <value>SomeUniqueKeyWithAGoodName/server/myService.asmx</value> </setting> </MyClient.Properties.Settings> </applicationSettings> </configuration> customized.targets: <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <BuildEnvironment>DEV</BuildEnvironment> </PropertyGroup> <Choose> <When Condition=" '$(BuildEnvironment)' == 'DEV' "> <PropertyGroup> <BaseUrlWebServices>http://tools.productionServer.pl</BaseUrlWebServices> <PublishDir>C:\Documents and Settings\myName\Desktop\Project\TestMsBuild\</PublishDir> </PropertyGroup> </When> <When Condition=" '$(BuildEnvironment)' == 'QA' "> <PropertyGroup> <BaseUrlWebServices>http://tools.testServer.pl</BaseUrlWebServices> <PublishDir>C:\Documents and Settings\myName\Desktop\Project\TestMsBuild2\</PublishDir> </PropertyGroup> </When> </Choose> </Project> and publishQA.bat (this file is in directory of project) @ECHO OFF msbuild /t:Publish /p:Configuration=Release /p:BuildEnvironment=QA /p:ApplicationVersion=1.2.3.5 pause When I'm running this bat I get error in cmd: @@echo is not recognised... When I'm starting project it's ok, but when I'm lauch try to use any method from webservice I got error about wrong URI. Good uri for QA is : http://tools.testServer.pl/server/myService.asmx Any ideas ?

    Read the article

  • DLL configuration file in asp.net site

    - by Tominator
    Hi, I've made a .net 2.0 librabry project, that results in a dll. I've made an app.config file in my project, with settings used in the dll, with the intention that they can be changed later. I'm attempting to use the dll in an asp.net web application now, so I made the reference to my other project's output, and I see that the dll is copied over to the site's bin folder, and everything works. However, the configuration file is not copied. When I manually copy the app.config and rename it to myDll.config, it has no influence. The contents of the config file is approximately this: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" > <section name="myDLL.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </sectionGroup> </configSections> <applicationSettings> <myDLL.My.MySettings> <setting name="myDLL_webservice_Service" serializeAs="String"> <value>https://myhost/Service.asmx</value> </setting> <setting name="ID" serializeAs="String"> <value>6</value> </setting> </myDLL.My.MySettings> </applicationSettings> </configuration> And I use its settings in the dll with this (vb.net code): Private _id As Long = My.Settings.ID How can I put my config information somewhere so it can be used? In the web.config of the site application? That has only the appSettings section, and it uses the syntax. It doesn't appear to work though. In a custom file format that I create and use? Not that pretty..

    Read the article

  • Log Blog

    - by PointsToShare
    © 2011 By: Dov Trietsch. All rights reserved Logging – A log blog In a another blog (Missing Fields and Defaults) I spoke about not doing a blog about log files, but then I looked at it again and realized that this is a nice opportunity to show a simple yet powerful tool and also deal with static variables and functions in C#. My log had to be able to answer a few simple logging rules:   To log or not to log? That is the question – Always log! That is the answer  Do we share a log? Even when a file is opened with a minimal lock, it does not share well and performance greatly suffers. So sharing a log is not a good idea. Also, when sharing, it is harder to find your particular entries and you have to establish rules about retention. My recommendation – Do Not Share!  How verbose? Your log can be very verbose – a good thing when testing, very terse – a good thing in day-to-day runs, or somewhere in between. You must be the judge. In my Blog, I elect to always report a run with start and end times, and always report errors. I normally use 5 levels of logging: 4 – write all, 3 – write more, 2 – write some, 1 – write errors and timing, 0 – write none. The code sample below is more general than that. It uses the config file to set the max log level and each call to the log assigns a level to the call itself. If the level is above the .config highest level, the line will not be written. Programmers decide which log belongs to which level and thus we can set the .config differently for production and testing.  Where do I keep the log? If your career is important to you, discuss this with the boss and with the system admin. We keep logs in the L: drive of our server and make sure that we have a directory for each app that needs a log. When adding a new app, add a new directory. The default location for the log is also found in the .config file Print One or Many? There are two options here:   1.     Print many, Open but once once – you start the stream and close it only when the program ends. This is what you can do when you perform in “batch” mode like in a console app or a stsadm extension.The advantage to this is that starting a closing a stream is expensive and time consuming and because we use a unique file, keeping it open for a long time does not cause contention problems. 2.     Print one entry at a time or Open many – every time you write a line, you start the stream, write to it and close it. This work for event receivers, feature receivers, and web parts. Here scalability requires us to create objects on the fly and get rid of them as soon as possible.  A default value of the onceOrMany resides in the .config.  All of the above applies to any windows or web application, not just SharePoint.  So as usual, here is a routine that does it all, and a few simple functions that call it for a variety of purposes.   So without further ado, here is app.config  <?xml version="1.0" encoding="utf-8" ?> <configuration>     <configSections>         <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, ublicKeyToken=b77a5c561934e089" >         <section name="statics.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />         </sectionGroup>     </configSections>     <applicationSettings>         <statics.Properties.Settings>             <setting name="oneOrMany" serializeAs="String">                 <value>False</value>             </setting>             <setting name="logURI" serializeAs="String">                 <value>C:\staticLog.txt</value>             </setting>             <setting name="highestLevel" serializeAs="String">                 <value>2</value>             </setting>         </statics.Properties.Settings>     </applicationSettings> </configuration>   And now the code:  In order to persist the variables between calls and also to be able to persist (or not to persist) the log file itself, I created an EventLog class with static variables and functions. Static functions do not need an instance of the class in order to work. If you ever wondered why our Main function is static, the answer is that something needs to run before instantiation so that other objects may be instantiated, and this is what the “static” Main does. The various logging functions and variables are created as static because they do not need instantiation and as a fringe benefit they remain un-destroyed between calls. The Main function here is just used for testing. Note that it does not instantiate anything, just uses the log functions. This is possible because the functions are static. Also note that the function calls are of the form: Class.Function.  using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace statics {       class Program     {         static void Main(string[] args)         {             //write a single line             EventLog.LogEvents("ha ha", 3, "C:\\hahafile.txt", 4, true, false);             //this single line will not be written because the msgLevel is too high             EventLog.LogEvents("baba", 3, "C:\\babafile.txt", 2, true, false);             //The next 4 lines will be written in succession - no closing             EventLog.LogLine("blah blah", 1);             EventLog.LogLine("da da", 1);             EventLog.LogLine("ma ma", 1);             EventLog.LogLine("lah lah", 1);             EventLog.CloseLog(); // log will close             //now with specific functions             EventLog.LogSingleLine("one line", 1);             //this is just a test, the log is already closed             EventLog.CloseLog();         }     }     public class EventLog     {         public static string logURI = Properties.Settings.Default.logURI;         public static bool isOneLine = Properties.Settings.Default.oneOrMany;         public static bool isOpen = false;         public static int highestLevel = Properties.Settings.Default.highestLevel;         public static StreamWriter sw;         /// <summary>         /// the program will "print" the msg into the log         /// unless msgLevel is > msgLimit         /// onceOrMany is true when once - the program will open the log         /// print the msg and close the log. False when many the program will         /// keep the log open until close = true         /// normally all the arguments will come from the app.config         /// called by many overloads of logLine         /// </summary>         /// <param name="msg"></param>         /// <param name="msgLevel"></param>         /// <param name="logFileName"></param>         /// <param name="msgLimit"></param>         /// <param name="onceOrMany"></param>         /// <param name="close"></param>         public static void LogEvents(string msg, int msgLevel, string logFileName, int msgLimit, bool oneOrMany, bool close)         {             //to print or not to print             if (msgLevel <= msgLimit)             {                 //open the file. from the argument (logFileName) or from the config (logURI)                 if (!isOpen)                 {                     string logFile = logFileName;                     if (logFileName == "")                     {                         logFile = logURI;                     }                     sw = new StreamWriter(logFile, true);                     sw.WriteLine("Started At: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));                     isOpen = true;                 }                 //print                 sw.WriteLine(msg);             }             //close when instructed             if (close || oneOrMany)             {                 if (isOpen)                 {                     sw.WriteLine("Ended At: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));                     sw.Close();                     isOpen = false;                 }             }         }           /// <summary>         /// The simplest, just msg and level         /// </summary>         /// <param name="msg"></param>         /// <param name="msgLevel"></param>         public static void LogLine(string msg, int msgLevel)         {             //use the given msg and msgLevel and all others are defaults             LogEvents(msg, msgLevel, "", highestLevel, isOneLine, false);         }                 /// <summary>         /// one line at a time - open print close         /// </summary>         /// <param name="msg"></param>         /// <param name="msgLevel"></param>         public static void LogSingleLine(string msg, int msgLevel)         {             LogEvents(msg, msgLevel, "", highestLevel, true, true);         }           /// <summary>         /// used to close. high level, low limit, once and close are set         /// </summary>         /// <param name="close"></param>         public static void CloseLog()         {             LogEvents("", 15, "", 1, true, true);         }           }     }   }   That’s all folks!

    Read the article

  • "Public" nested classes or not

    - by Frederick
    Suppose I have a class 'Application'. In order to be initialised it takes certain settings in the constructor. Let's also assume that the number of settings is so many that it's compelling to place them in a class of their own. Compare the following two implementations of this scenario. Implementation 1: class Application { Application(ApplicationSettings settings) { //Do initialisation here } } class ApplicationSettings { //Settings related methods and properties here } Implementation 2: class Application { Application(Application.Settings settings) { //Do initialisation here } class Settings { //Settings related methods and properties here } } To me, the second approach is very much preferable. It is more readable because it strongly emphasises the relation between the two classes. When I write code to instantiate Application class anywhere, the second approach is going to look prettier. Now just imagine the Settings class itself in turn had some similarly "related" class and that class in turn did so too. Go only three such levels and the class naming gets out out of hand in the 'non-nested' case. If you nest, however, things still stay elegant. Despite the above, I've read people saying on StackOverflow that nested classes are justified only if they're not visible to the outside world; that is if they are used only for the internal implementation of the containing class. The commonly cited objection is bloating the size of containing class's source file, but partial classes is the perfect solution for that problem. My question is, why are we wary of the "publicly exposed" use of nested classes? Are there any other arguments against such use?

    Read the article

  • VB.Net Application Settings / ClickOnce

    - by B Z
    VS 2008 / VB.Net / WinForms I have an application setting (Settings.settings) for a project and I am using Click Once deployment. I used the VS Editor to create the setting and I can see the setting in the app.config file <applicationSettings> <MyApp.Win.My.MySettings> <setting name="MySetting" serializeAs="String"> <value>False</value> </setting> </MyApp.ArtTracker.Win.My.MySettings> </applicationSettings> I would like to update this setting after the application is compiled. The setting is for testing purposes only. If I change the xxx.config.deploy and I reinstall the app with click once. The new setting value doesn't change (seems to be cached somewhere). Even if I change in my local pc the setting seems to be cached somewhere. If I go in VS it asks me to Re-Sync the settings. But I need to do this after the application is compiled. Thanks for any help

    Read the article

  • Windows Phone 7: Building a simple dictionary web client

    - by TechTwaddle
    Like I mentioned in this post a while back, I came across a dictionary web service called Aonaware that serves up word definitions from various dictionaries and is really easy to use. The services page on their website, http://services.aonaware.com/DictService/DictService.asmx, lists all the operations that are supported by the dictionary service. Here they are, Word Dictionary Web Service The following operations are supported. For a formal definition, please review the Service Description. Define Define given word, returning definitions from all dictionaries DefineInDict Define given word, returning definitions from specified dictionary DictionaryInfo Show information about the specified dictionary DictionaryList Returns a list of available dictionaries DictionaryListExtended Returns a list of advanced dictionaries (e.g. translating dictionaries) Match Look for matching words in all dictionaries using the given strategy MatchInDict Look for matching words in the specified dictionary using the given strategy ServerInfo Show remote server information StrategyList Return list of all available strategies on the server Follow the links above to get more information on each API. In this post we will be building a simple windows phone 7 client which uses this service to get word definitions for words entered by the user. The application will also allow the user to select a dictionary from all the available ones and look up the word definition in that dictionary. So of all the apis above we will be using only two, DictionaryList() to get a list of all supported dictionaries and DefineInDict() to get the word definition from a particular dictionary. Before we get started, a note to you all; I would have liked to implement this application using concepts from data binding, item templates, data templates etc. I have a basic understanding of what they are but, being a beginner, I am not very comfortable with those topics yet so I didn’t use them. I thought I’ll get this version out of the way and maybe in the next version I could give those a try. A somewhat scary mock-up of the what the final application will look like, Select Dictionary is a list picker control from the silverlight toolkit (you need to download and install the toolkit if you haven’t already). Below it is a textbox where the user can enter words to look up and a button beside it to fetch the word definition when clicked. Finally we have a textblock which occupies the remaining area and displays the word definition from the selected dictionary. Create a silverlight application for windows phone 7, AonawareDictionaryClient, and add references to the silverlight toolkit and the web service. From the solution explorer right on References and select Microsoft.Phone.Controls.Toolkit from under the .NET tab, Next, add a reference to the web service. Again right click on References and this time select Add Service Reference In the resulting dialog paste the service url in the Address field and press go, (url –> http://services.aonaware.com/DictService/DictService.asmx) once the service is discovered, provide a name for the NameSpace, in this case I’ve called it AonawareDictionaryService. Press OK. You can now use the classes and functions that are generated in the AonawareDictionaryClient.AonawareDictionaryService namespace. Let’s get the UI done now. In MainPage.xaml add a namespace declaration to use the toolkit controls, xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit" the content of LayoutRoot is changed as follows, (sorry, no syntax highlighting in this post) <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,5,0,5">     <TextBlock x:Name="ApplicationTitle" Text="AONAWARE DICTIONARY CLIENT" Style="{StaticResource PhoneTextNormalStyle}"/>     <!--<TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>--> </StackPanel> <!--ContentPanel - place additional content here--> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">     <Grid.RowDefinitions>         <RowDefinition Height="Auto"/>         <RowDefinition Height="Auto"/>         <RowDefinition Height="*"/>     </Grid.RowDefinitions>     <toolkit:ListPicker Grid.Column="1" x:Name="listPickerDictionaryList"                         Header="Select Dictionary :">     </toolkit:ListPicker>     <Grid Grid.Row="1" Margin="0,5,0,0">         <Grid.ColumnDefinitions>             <ColumnDefinition Width="*"/>             <ColumnDefinition Width="Auto" />         </Grid.ColumnDefinitions>         <TextBox x:Name="txtboxInputWord" Grid.Column="0" GotFocus="OnTextboxInputWordGotFocus" />         <Button x:Name="btnGo" Grid.Column="1" Click="OnButtonGoClick" >             <Button.Content>                 <Image Source="/images/button-go.png"/>             </Button.Content>         </Button>     </Grid>     <ScrollViewer Grid.Row="2" x:Name="scrollViewer">         <TextBlock  Margin="12,5,12,5"  x:Name="txtBlockWordMeaning" HorizontalAlignment="Stretch"                    VerticalAlignment="Stretch" TextWrapping="Wrap"                    FontSize="26" />     </ScrollViewer> </Grid> I have commented out the PageTitle as it occupies too much valuable space, and the ContentPanel is changed to contain three rows. First row contains the list picker control, second row contains the textbox and the button, and the third row contains a textblock within a scroll viewer. The designer will now be showing the final ui, Now go to MainPage.xaml.cs, and add the following namespace declarations, using Microsoft.Phone.Controls; using AonawareDictionaryClient.AonawareDictionaryService; using System.IO.IsolatedStorage; A class called DictServiceSoapClient would have been created for you in the background when you added a reference to the web service. This class functions as a wrapper to the services exported by the web service. All the web service functions that we saw at the start can be access through this class, or more precisely through an object of this class. Create a data member of type DictServiceSoapClient in the Mainpage class, and a function which initializes it, DictServiceSoapClient DictSvcClient = null; private DictServiceSoapClient GetDictServiceSoapClient() {     if (null == DictSvcClient)     {         DictSvcClient = new DictServiceSoapClient();     }     return DictSvcClient; } We have two major tasks remaining. First, when the application loads we need to populate the list picker with all the supported dictionaries and second, when the user enters a word and clicks on the arrow button we need to fetch the word’s meaning. Populating the List Picker In the OnNavigatingTo event of the MainPage, we call the DictionaryList() api. This can also be done in the OnLoading event handler of the MainPage; not sure if one has an advantage over the other. Here’s the code for OnNavigatedTo, protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) {     DictServiceSoapClient client = GetDictServiceSoapClient();     client.DictionaryListCompleted += new EventHandler<DictionaryListCompletedEventArgs>(OnGetDictionaryListCompleted);     client.DictionaryListAsync();     base.OnNavigatedTo(e); } Windows Phone 7 supports only async calls to web services. When we added a reference to the dictionary service, asynchronous versions of all the functions were generated automatically. So in the above function we register a handler to the DictionaryListCompleted event which will occur when the call to DictionaryList() gets a response from the server. Then we call the DictionaryListAsynch() function which is the async version of the DictionaryList() api. The result of this api will be sent to the handler OnGetDictionaryListCompleted(), void OnGetDictionaryListCompleted(object sender, DictionaryListCompletedEventArgs e) {     IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;     Dictionary[] listOfDictionaries;     if (e.Error == null)     {         listOfDictionaries = e.Result;         PopulateListPicker(listOfDictionaries, settings);     }     else if (settings.Contains("SavedDictionaryList"))     {         listOfDictionaries = settings["SavedDictionaryList"] as Dictionary[];         PopulateListPicker(listOfDictionaries, settings);     }     else     {         MessageBoxResult res = MessageBox.Show("An error occured while retrieving dictionary list, do you want to try again?", "Error", MessageBoxButton.OKCancel);         if (MessageBoxResult.OK == res)         {             GetDictServiceSoapClient().DictionaryListAsync();         }     }     settings.Save(); } I have used IsolatedStorageSettings to store a few things; the entire dictionary list and the dictionary that is selected when the user exits the application, so that the next time when the user starts the application the current dictionary is set to the last selected value. First we check if the api returned any error, if the error object is null e.Result will contain the list (actually array) of Dictionary type objects. If there was an error, we check the isolated storage settings to see if there is a dictionary list stored from a previous instance of the application and if so, we populate the list picker based on this saved list. Note that in this case there are chances that the dictionary list might be out of date if there have been changes on the server. Finally, if none of these cases are true, we display an error message to the user and try to fetch the list again. PopulateListPicker() is passed the array of Dictionary objects and the settings object as well, void PopulateListPicker(Dictionary[] listOfDictionaries, IsolatedStorageSettings settings) {     listPickerDictionaryList.Items.Clear();     foreach (Dictionary dictionary in listOfDictionaries)     {         listPickerDictionaryList.Items.Add(dictionary.Name);     }     settings["SavedDictionaryList"] = listOfDictionaries;     string savedDictionaryName;     if (settings.Contains("SavedDictionary"))     {         savedDictionaryName = settings["SavedDictionary"] as string;     }     else     {         savedDictionaryName = "WordNet (r) 2.0"; //default dictionary, wordnet     }     foreach (string dictName in listPickerDictionaryList.Items)     {         if (dictName == savedDictionaryName)         {             listPickerDictionaryList.SelectedItem = dictName;             break;         }     }     settings["SavedDictionary"] = listPickerDictionaryList.SelectedItem as string; } We first clear all the items from the list picker, add the dictionary names from the array and then create a key in the settings called SavedDictionaryList and store the dictionary list in it. We then check if there is saved dictionary available from a previous instance, if there is, we set it as the selected item in the list picker. And if not, we set “WordNet ® 2.0” as the default dictionary. Before returning, we save the selected dictionary in the “SavedDictionary” key of the isolated storage settings. Fetching word definitions Getting this part done is very similar to the above code. We get the input word from the textbox, call into DefineInDictAsync() to fetch the definition and when DefineInDictAsync completes, we get the result and display it in the textblock. Here is the handler for the button click, private void OnButtonGoClick(object sender, RoutedEventArgs e) {     txtBlockWordMeaning.Text = "Please wait..";     IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;     if (txtboxInputWord.Text.Trim().Length <= 0)     {         MessageBox.Show("Please enter a word in the textbox and press 'Go'");     }     else     {         Dictionary[] listOfDictionaries = settings["SavedDictionaryList"] as Dictionary[];         string selectedDictionary = listPickerDictionaryList.SelectedItem.ToString();         string dictId = "wn"; //default dictionary is wordnet (wn is the dict id)         foreach (Dictionary dict in listOfDictionaries)         {             if (dict.Name == selectedDictionary)             {                 dictId = dict.Id;                 break;             }         }         DictServiceSoapClient client = GetDictServiceSoapClient();         client.DefineInDictCompleted += new EventHandler<DefineInDictCompletedEventArgs>(OnDefineInDictCompleted);         client.DefineInDictAsync(dictId, txtboxInputWord.Text.Trim());     } } We validate the input and then select the dictionary id based on the currently selected dictionary. We need the dictionary id because the api DefineInDict() expects the dictionary identifier and not the dictionary name. We could very well have stored the dictionary id in isolated storage settings too. Again, same as before, we register a event handler for the DefineInDictCompleted event and call the DefineInDictAsync() method passing in the dictionary id and the input word. void OnDefineInDictCompleted(object sender, DefineInDictCompletedEventArgs e) {     WordDefinition wd = e.Result;     scrollViewer.ScrollToVerticalOffset(0.0f);     if (wd.Definitions.Length == 0)     {         txtBlockWordMeaning.Text = String.Format("No definitions were found for '{0}' in '{1}'", txtboxInputWord.Text.Trim(), listPickerDictionaryList.SelectedItem.ToString().Trim());     }     else     {         foreach (Definition def in wd.Definitions)         {             string str = def.WordDefinition;             str = str.Replace("  ", " "); //some formatting             txtBlockWordMeaning.Text = str;         }     } } When the api completes, e.Result will contain a WordDefnition object. This class is also generated in the background while adding the service reference. We check the word definitions within this class to see if any results were returned, if not, we display a message to the user in the textblock. If a definition was found the text on the textblock is set to display the definition of the word. Adding final touches, we now need to save the current dictionary when the application exits. A small but useful thing is selecting the entire word in the input textbox when the user selects it. This makes sure that if the user has looked up a definition for a really long word, he doesn’t have to press ‘clear’ too many times to enter the next word, protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e) {     IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;     settings["SavedDictionary"] = listPickerDictionaryList.SelectedItem as string;     settings.Save();     base.OnNavigatingFrom(e); } private void OnTextboxInputWordGotFocus(object sender, RoutedEventArgs e) {     TextBox txtbox = sender as TextBox;     if (txtbox.Text.Trim().Length > 0)     {         txtbox.SelectionStart = 0;         txtbox.SelectionLength = txtbox.Text.Length;     } } OnNavigatingFrom() is called whenever you navigate away from the MainPage, since our application contains only one page that would mean that it is exiting. I leave you with a short video of the application in action, but before that if you have any suggestions on how to make the code better and improve it please do leave a comment. Until next time…

    Read the article

  • Persistent Storage in Windows Phone 7

    - by Richard Jones
    Mark Arteaga – fellow MVP just helped me with this,  thought I’d share. Windows Phone 7 SilverLight supports persistent storage, which is a great way of saving settings betweens runs of your application. However I couldn’t get it to work. If you do this to create a persistant storage instance -    private IsolatedStorageSettings userSettings = IsolatedStorageSettings.ApplicationSettings; To retrieve settings do the following - string xx = userSettings[“SomeValue”].ToString();   Hiowever the bit that got me was how to save settings, you have todo this - userSettings.Add("Hello", DateTime.Now.ToShortTimeString());           userSettings.Save(); // <- This is the bit that got me   Hope this helps others

    Read the article

  • Two way binding settings problem.

    - by Jamie
    Hi, I am having a problem using two way binding with a listpicker. I am able to set the value using c# but not in the SelectedItem=".." in xaml. The binding is returning the correct value (and is a value in the listpicker) as i have texted it by assigning the text to a textblock. When the page loads, the binding used on the listpicker causes a System.ArgumentOutOfRangeException The code i am using to set it is: // Update a setting value. If the setting does not exist, add the setting. public bool AddOrUpdateValue(string key, Object value) { bool valueChanged = false; try { // If new value is different, set the new value if (settingsStorage[key] != value) { settingsStorage[key] = value; valueChanged = true; } } catch (KeyNotFoundException) { settingsStorage.Add(key, value); valueChanged = true; } catch (ArgumentException) { settingsStorage.Add(key, value); valueChanged = true; } catch (Exception e) { Console.WriteLine("Exception occured whilst using IsolatedStorageSettings: " + e.ToString()); } return valueChanged; } // Get the current value of the setting, if not found, set the setting to default value. public valueType GetValueOrDefault<valueType>(string key, valueType defaultValue) { valueType value; try { value = (valueType)settingsStorage[key]; } catch (KeyNotFoundException) { value = defaultValue; } catch (ArgumentException) { value = defaultValue; } return value; } public string WeekBeginsSetting { get { return GetValueOrDefault<string>(WeekBeginsSettingKeyName, WeekBeginsSettingDefault); } set { AddOrUpdateValue(WeekBeginsSettingKeyName, value); Save(); } } And in the xaml: <toolkit:ListPicker x:Name="WeekStartDay" Header="Week begins on" SelectedItem="{Binding Source={StaticResource AppSettings}, Path=WeekBeginsSetting, Mode=TwoWay}"> <sys:String>monday</sys:String> <sys:String>sunday</sys:String> </toolkit:ListPicker> The StaticResource AppSettings is a resource from a seperate .cs file. <phone:PhoneApplicationPage.Resources> <local:ApplicationSettings x:Key="AppSettings"></local:ApplicationSettings> </phone:PhoneApplicationPage.Resources> Thanks in advance

    Read the article

  • Bi-directional WCF Client-Server Communication

    - by Bill
    I have been working for weeks on creating a client/server to control a music-server application located on the server-side that is controlled by several client apps located across the LAN. I've been successful in getting the client-side to communicate with the Server, sending commands to operate the music-server, and through the use of callbacks, reply to the clients so that all of the client UI's can be appropriately updated. My problem is however, that I unable to figure-out how to broadcast other messages that need to be sent from the server app to the clients. I was hoping to utilize the callback method; however I have not been able to access it from the server side. Do I need to modify or create another contract that provides for communication from the server to the clients? Does the binding require modification? As I mentioned earlier, I have truly been working on this for weeks (which is beginning to feel like 'years'), and hope to get this last piece of the application working. Would someone please steer me in the right direction? Client Side SERVICE REFERENCE: <?xml version="1.0" encoding="utf-8"?> <ServiceReference> <ProxyGenerationParameters ServiceReferenceUri="http://localhost:8001/APService/mex" Name="APGateway" NotifyPropertyChange="True" UseObservableCollection="False"> </ProxyGenerationParameters> <EndPoints> <EndPoint Address="net.tcp://localhost:8000/APService/service" BindingConfiguration="TcpBinding" Contract="APClient.APGateway.APUserService" > </EndPoint> <EndPoint Address="http://localhost:8001/APService/service" BindingConfiguration="HttpBinding" Contract="APClient.APGateway.APUserService" > </EndPoint> </EndPoints> </ServiceReference> Client Side AP CONFIG <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" > <section name="APClient.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </sectionGroup> </configSections> <system.serviceModel> <client> <endpoint address="net.tcp://localhost:8000/APService/service" binding="netTcpBinding" contract="APClient.APGateway.APUserService" name="TcpBinding" /> <endpoint address="http://localhost:8001/APService/service" binding="wsDualHttpBinding" contract="APClient.APGateway.APUserService" name="HttpBinding" /> </client> </system.serviceModel> <applicationSettings> <APClient.Properties.Settings> <setting name="pathToDatabase" serializeAs="String"> <value>C:\Users\Bill\Documents\APData\</value> </setting> </APClient.Properties.Settings> </applicationSettings> Server Side AP.CONFIG <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="MetadataBehavior"> <serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8001/APService/mex" /> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="MetadataBehavior" name="APService.APService"> <endpoint address="service" binding="netTcpBinding" name="TcpBinding" contract="APService.IAPServiceInventory" /> <endpoint address="service" binding="wsDualHttpBinding" name="HttpBinding" contract="APService.IAPServiceInventory" /> <endpoint address="mex" binding="mexHttpBinding" name="MexBinding" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="net.tcp://localhost:8000/APService/" /> <add baseAddress="http://localhost:8001/APService/" /> </baseAddresses> </host> </service> </services> </system.serviceModel> </configuration> Server Side APSERVICE.CS namespace APService { [ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Single,InstanceContextMode=InstanceContextMode.PerCall)] public class APService : IAPServiceInventory { private static List<IClientCallback> _callbackList = new List<IClientCallback>(); private static int _beerInventory = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["InitialBeerInventory"]); public APService() {} public int SubscribeToServer(string guestName) { IClientCallback guest = OperationContext.Current.GetCallbackChannel<IClientCallback>(); if(!_callbackList.Contains(guest)) { _callbackList.Add(guest); } else { Console.WriteLine(guest + " is already logged onto the Server."); } _callbackList.ForEach(delegate(IClientCallback callback) { callback.NotifyGuestJoinedParty(guestName); }); } public void UpdateClients(string guestName,string UpdateInfo) { _callbackList.ForEach(delegate(IClientCallback callback) { callback.NotifyUpdateClients(guestName,UpdateInfo); }); } public void SendRequestToServer(string guestName, string request) { _callbackList.ForEach(delegate(IClientCallback callback) { callback.NotifyRequestMadeToServer(guestName,request); }); if(request == "Play") { APControl.Play(); } else if(request == "Stop") { APControl.Stop(); } else if(request == "Pause") { APControl.PlayPause(); } else if(request == "Next Track") { APControl.NextTrack(); } else if(request == "Previous Track") { APControl.PreviousTrack(); } else if(request == "Mute") { APControl.Mute(); } else if(request == "Volume Up") { APControl.VolumeUp(5); } else if(request == "Volume Down") { APControl.VolumeDown(5); } } public void CancelServerSubscription(string guestName) { IClientCallback guest = OperationContext.Current.GetCallbackChannel<IClientCallback>(); if(_callbackList.Contains(guest)) { _callbackList.Remove(guest); } _callbackList.ForEach(delegate(IClientCallback callback) { callback.NotifyGuestLeftParty(guestName); }); } } Server Side IAPSERVICE.CS namespace APService { [ServiceContract(Name="APUserService",Namespace="http://AP.com/WCFClientServer/",SessionMode=SessionMode.Required, CallbackContract=typeof(IClientCallback))] public interface IAPServiceInventory { [OperationContract()] int SubscribeToServer(string guestName); [OperationContract(IsOneWay=true)] void SendRequestToServer(string guestName,string request); [OperationContract(IsOneWay=true)] void UpdateClients(string guestName,string UpdateInfo); [OperationContract(IsOneWay=true)] void CancelServerSubscription(string guestName); } } Server side - IAPServiceCallback.cs namespace APService { public interface IClientCallback { [OperationContract(IsOneWay=true)] void NotifyGuestJoinedParty(string guestName); [OperationContract(IsOneWay=true)] void NotifyUpdateClients(string guestName,string UpdateInfo); [OperationContract(IsOneWay=true)] void NotifyRequestMadeToServer(string guestName,string request); [OperationContract(IsOneWay=true)] void NotifyGuestLeftParty(string guestName); }

    Read the article

  • Calling Property Methods from the e.PropertyName property

    - by user275561
    void TheSettings_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { var settings = IsolatedStorageSettings.ApplicationSettings[StorageSettings] as Dictionary<string, string>; settings[e.PropertyName]= //call the method that has the same property name to get what the value is LoadData(); } Here is What I am trying to do. This is for a Windows Phone 7 series App. I am trying to determine what values got changed when the user changes the settings on the settings page and just save that.

    Read the article

1 2  | Next Page >