Search Results

Search found 179 results on 8 pages for 'defaultvalue'.

Page 1/8 | 1 2 3 4 5 6 7 8  | Next Page >

  • Spring MVC defaultValue for Double

    - by mlathe
    Hi All, I'm trying to build a controller like this: @RequestMapping(method = {RequestMethod.GET}, value = "/users/detail/activities.do") public View foo(@RequestParam(value = "userCash", defaultValue="0.0") Double userCash) { System.out.println("foo userCash=" + userCash); } This works fine: http://localhost/app/users/detail/activities.do?userCash=123& but in this one userCash==null despite the default value http://localhost/app/users/detail/activities.do?userCash=& From some digging it seems like the first one works b/c of a Editor binding like this: binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, false)); The trouble is that the second param (ie false) defines whether blank values are allowed. If i set that to true, than the system considers the blank input as valid so i get a null Double class. If i set it to false then the system chokes on the blank input string with: org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'double'; nested exception is java.lang.NumberFormatException: empty String Does anyone know how to get the defaultValue to work for Doubles? Thanks --Matthias

    Read the article

  • .NET DefaultValue attribute

    - by Aaron
    I've heard people say a few different things about the DefaultValue attribute including: "It sets the value of the property before anything else uses it." "It doesn't work for autoproperties." "It's only for decoration. You must manually set actual default values." Which (if any) is right? Does DefaultValue actually set default values? Are there cases where it doesn't work? Is it best just not to use it?

    Read the article

  • ASP.NET ObjectDataSource, change CommandName property of FromView Button

    - by Tone
    I have an ObjectDataSource that I'm using with a FormView, and it works fine, but i want to change one small thing. On the FormView the button that fires the update has the CommandName attribute set to "Update," but I would like to change that attribute to something other than "Update" - when I do change that attribute the update no longer works. The reason I want to do this is I have multiple FormViews on the same page and need to have multiple update buttons. Below is my code: FormView: <asp:FormView ID="fvGeneralInfo" runat="server" DataSourceID="objInstructorDetails" CssClass="Gridview" OnItemCommand="fvGeneralInfo_ItemCommand" DefaultMode="Edit"> <EditItemTemplate> <table> .... <tr> <td style="text-align:right;"> <asp:Label runat="server" ID="lblGeneralInfoMessage" Text="General Info updated successfully" Visible="false" /> </td> <td> <asp:Button runat="server" ID="btnUpdateGeneralInfo" ValidationGroup="UpdateGeneralInfo" Text="Update" CommandName="Update" /> <asp:Button runat="server" ID="btnCancelGeneralInfo" Text="Cancel" CommandName="CancelGeneralInfo" /> </td> </tr> </table> </EditItemTemplate> </asp:FormView> ObjectDataSource: <asp:ObjectDataSource ID="objInstructorDetails" runat="server" TypeName="AIMLibrary.BLL.Instructor" SelectMethod="GetInstructorDetails" InsertMethod="InsertInstructor" UpdateMethod="UpdateInstructor" OnInserting="objInstructorDetails_OnInserting" OnUpdating="objInstructorDetails_OnUpdating" > <SelectParameters> <asp:QueryStringParameter Name="InstructorId" QueryStringField="InstructorId" /> </SelectParameters> <UpdateParameters> <asp:Parameter Name="instructorId" Type="Int32" /> <asp:Parameter Name="firstName" Type="String" DefaultValue="" /> <asp:Parameter Name="middleName" Type="String" DefaultValue="" /> <asp:Parameter Name="lastName" Type="String" DefaultValue="" /> <asp:Parameter Name="phone" Type="String" DefaultValue="" /> <asp:Parameter Name="email" Type="String" DefaultValue="" /> <asp:Parameter Name="addressLine1" Type="String" DefaultValue="" /> <asp:Parameter Name="addressLine2" Type="String" DefaultValue="" /> <asp:Parameter Name="city" Type="String" DefaultValue="" /> <asp:Parameter Name="state" Type="String" DefaultValue="" /> <asp:Parameter Name="zip" Type="String" DefaultValue="" /> <asp:Parameter Name="abcBoardNumber" Type="String" DefaultValue="" /> </UpdateParameters> </asp:ObjectDataSource>

    Read the article

  • SOAP call with query on result (SSRS, Sharepoint)

    - by Erik404
    Hi! I created a report in VS using a shared data source which is connected to a sharepoint list. In the report I created a dataset with a SOAP call to the data source so I get the result from the sharepoint list in a table. this is the soap call <Query> <SoapAction>http://schemas.microsoft.com/sharepoint/soap/GetListItems</SoapAction> <Method Namespace="http://schemas.microsoft.com/sharepoint/soap/" Name="GetListItems"> <Parameters> <Parameter Name="listName"> <DefaultValue>{BD8D39B7-FA0B-491D-AC6F-EC9B0978E0CE}</DefaultValue> </Parameter> <Parameter Name="viewName"> <DefaultValue>{E2168426-804F-4836-9BE4-DC5F8D08A54F}</DefaultValue> </Parameter> <Parameter Name="rowLimit"> <DefaultValue>9999</DefaultValue> </Parameter> </Parameters> </Method> <ElementPath IgnoreNamespaces="True">*</ElementPath> </Query> THis works fine, I have a result which I can show in a report, but I want to have the ability to select a parameter to filter the result on. I have created a parameter and when I preview the Report I see the dropdownbox which I can use to make a selection from the Title field, when I do this it still shows the first record, obviously it doens't work yet (DUH!) because I need to create a query somewhere, But! I have no idea where, I tried to include <Where> <Eq> <FieldRef Name="ows_Title" /> <Value Type="Text">testValue</Value> </Eq> </Where> in the the soap request but it didn't worked... I've searched teh intarwebz but couldn't find any simliar problems... kinda stuck now...any thoughts on this? EDIT Here's the query I used according to the blogpost Alex Angas linked. <Query> <SoapAction>http://schemas.microsoft.com/sharepoint/soap/GetListItems</SoapAction> <Method Namespace="http://schemas.microsoft.com/sharepoint/soap/" Name="GetListItems"> <queryOptions></queryOptions> <query><Query> <Where> <Eq> <FieldRef Name="ows_Title"/> <Value Type="Text">someValue</Value> </Eq> </Where> </Query></query> <Parameters> <Parameter Name="listName"> <DefaultValue>{BD8D39B7-FA0B-491D-AC6F-EC9B0978E0CE}</DefaultValue> </Parameter> <Parameter Name="viewName"> <DefaultValue>{E2168426-804F-4836-9BE4-DC5F8D08A54F}</DefaultValue> </Parameter> <Parameter Name="rowLimit"> <DefaultValue>9999</DefaultValue> </Parameter> </Parameters> </Method> <ElementPath IgnoreNamespaces="True">*</ElementPath> </Query> I tried to put the new query statement in every possible way in the existing, but it doesn't work at all, I do not get an error though so the code is valid, but I still get an unfiltered list as return... pulling my hair out here!

    Read the article

  • ASP.NET List Control

    - by Ricardo Peres
    Today I developed a simple control for generating lists in ASP.NET, something that the base class library does not contain; it allows for nested lists where the list item types and images can be configured on a list by list basis. Since it was a great fun to develop, I'd like to share it here. Here is the code: [ParseChildren(true)] [PersistChildren(false)] public class List: WebControl { public List(): base("ul") { this.Items = new List(); this.ListStyleType = ListStyleType.Auto; this.ListStyleImageUrl = String.Empty; this.CommonCssClass = String.Empty; this.ContainerCssClass = String.Empty; } [DefaultValue(ListStyleType.Auto)] public ListStyleType ListStyleType { get; set; } [DefaultValue("")] [UrlProperty("*.png;*.gif;*.jpg")] public String ListStyleImageUrl { get; set; } [DefaultValue("")] [CssClassProperty] public String CommonCssClass { get; set; } [DefaultValue("")] [CssClassProperty] public String ContainerCssClass { get; set; } [Browsable(false)] [PersistenceModeAttribute(PersistenceMode.InnerProperty)] public List Items { private set; get; } protected override void Render(HtmlTextWriter writer) { String cssClass = String.Join(" ", new String [] { this.CssClass, this.ContainerCssClass }); if (cssClass.Trim().Length != 0) { this.CssClass = cssClass; } if (String.IsNullOrEmpty(this.ListStyleImageUrl) == false) { this.Style[ HtmlTextWriterStyle.ListStyleImage ] = String.Format("url('{0}')", this.ResolveClientUrl(this.ListStyleImageUrl)); } if (this.ListStyleType != ListStyleType.Auto) { switch (this.ListStyleType) { case ListStyleType.Circle: case ListStyleType.Decimal: case ListStyleType.Disc: case ListStyleType.None: case ListStyleType.Square: this.Style [ HtmlTextWriterStyle.ListStyleType ] = this.ListStyleType.ToString().ToLower(); break; case ListStyleType.LowerAlpha: this.Style [ HtmlTextWriterStyle.ListStyleType ] = "lower-alpha"; break; case ListStyleType.LowerRoman: this.Style [ HtmlTextWriterStyle.ListStyleType ] = "lower-roman"; break; case ListStyleType.UpperAlpha: this.Style [ HtmlTextWriterStyle.ListStyleType ] = "upper-alpha"; break; case ListStyleType.UpperRoman: this.Style [ HtmlTextWriterStyle.ListStyleType ] = "upper-roman"; break; } } base.Render(writer); } protected override void RenderChildren(HtmlTextWriter writer) { foreach (ListItem item in this.Items) { this.writeItem(item, this, 0); } base.RenderChildren(writer); } private void writeItem(ListItem item, Control control, Int32 depth) { HtmlGenericControl li = new HtmlGenericControl("li"); control.Controls.Add(li); if (String.IsNullOrEmpty(this.CommonCssClass) == false) { String cssClass = String.Join(" ", new String [] { this.CommonCssClass, this.CommonCssClass + depth }); li.Attributes [ "class" ] = cssClass; } foreach (String key in item.Attributes.Keys) { li.Attributes[key] = item.Attributes [ key ]; } li.InnerText = item.Text; if (item.ChildItems.Count != 0) { HtmlGenericControl ul = new HtmlGenericControl("ul"); li.Controls.Add(ul); if (String.IsNullOrEmpty(this.ContainerCssClass) == false) { ul.Attributes["class"] = this.ContainerCssClass; } if ((item.ListStyleType != ListStyleType.Auto) || (String.IsNullOrEmpty(item.ListStyleImageUrl) == false)) { if (String.IsNullOrEmpty(item.ListStyleImageUrl) == false) { ul.Style[HtmlTextWriterStyle.ListStyleImage] = String.Format("url('{0}');", this.ResolveClientUrl(item.ListStyleImageUrl)); } if (item.ListStyleType != ListStyleType.Auto) { switch (this.ListStyleType) { case ListStyleType.Circle: case ListStyleType.Decimal: case ListStyleType.Disc: case ListStyleType.None: case ListStyleType.Square: ul.Style[ HtmlTextWriterStyle.ListStyleType ] = item.ListStyleType.ToString().ToLower(); break; case ListStyleType.LowerAlpha: ul.Style [ HtmlTextWriterStyle.ListStyleType ] = "lower-alpha"; break; case ListStyleType.LowerRoman: ul.Style [ HtmlTextWriterStyle.ListStyleType ] = "lower-roman"; break; case ListStyleType.UpperAlpha: ul.Style [ HtmlTextWriterStyle.ListStyleType ] = "upper-alpha"; break; case ListStyleType.UpperRoman: ul.Style [ HtmlTextWriterStyle.ListStyleType ] = "upper-roman"; break; } } } foreach (ListItem childItem in item.ChildItems) { this.writeItem(childItem, ul, depth + 1); } } } } [Serializable] [ParseChildren(true, "ChildItems")] public class ListItem: IAttributeAccessor { public ListItem() { this.ChildItems = new List(); this.Attributes = new Dictionary(); this.Text = String.Empty; this.Value = String.Empty; this.ListStyleType = ListStyleType.Auto; this.ListStyleImageUrl = String.Empty; } [DefaultValue(ListStyleType.Auto)] public ListStyleType ListStyleType { get; set; } [DefaultValue("")] [UrlProperty("*.png;*.gif;*.jpg")] public String ListStyleImageUrl { get; set; } [DefaultValue("")] public String Text { get; set; } [DefaultValue("")] public String Value { get; set; } [Browsable(false)] public List ChildItems { get; private set; } [Browsable(false)] public Dictionary Attributes { get; private set; } String IAttributeAccessor.GetAttribute(String key) { return (this.Attributes [ key ]); } void IAttributeAccessor.SetAttribute(String key, String value) { this.Attributes [ key ] = value; } } [Serializable] public enum ListStyleType { Auto = 0, Disc, Circle, Square, Decimal, LowerRoman, UpperRoman, LowerAlpha, UpperAlpha, None } SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf'; SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp']; SyntaxHighlighter.all();

    Read the article

  • Is this the best approach using generics to check for nulls

    - by user294747
    public static T IsNull<T>(object value, T defaultValue) { turn ((Object.Equals(value,null)) | (Object.Equals(value,DBNull.Value)) ? defaultValue : (T)value); } public static T IsNull<T>(object value) where T :new() { T defaultvalue = new T(); return IsNull(value, defaultvalue); } Have tested, and can use against data objects, classes and variables. Just want to know if there is better way to go about this.

    Read the article

  • Create Generic method constraining T to an Enum

    - by johnc
    I'm building a function to extend the Enum.Parse concept that allows a default value to be parsed in case that an Enum value is not found Is case insensitive So I wrote the following public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum { if (string.IsNullOrEmpty(value)) return defaultValue; foreach (T item in Enum.GetValues(typeof(T))) { if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item; } return defaultValue; } I am getting a Error Constraint cannot be special class 'System.Enum' Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the Parse function and pass a type as an attribute, which forces the ugly boxing requirement to your code. EDIT All suggestions below have been greatly appreciated, thanks Have settled on (I've left the loop to maintain case insensitivity - I am usng this when parsing XML) public static class EnumUtils { public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible { if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type"); if (string.IsNullOrEmpty(value)) return defaultValue; foreach (T item in Enum.GetValues(typeof(T))) { if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item; } return defaultValue; } }

    Read the article

  • Insert default value if input-text is deleted

    - by Kim Andersen
    Hi all I have the following piece of jQuery code: $(".SearchForm input:text").each(function(){ /* Sets the current value as the defaultvalue attribute */ if(allowedDefaults.indexOf($(this).val()) > 0 || $(this).val() == "") { $(this).attr("defaultvalue", $(this).val()); $(this).css("color","#9d9d9d"); /* Onfocus, if default value clear the field */ $(this).focus(function(){ if($(this).val() == $(this).attr("defaultvalue")) { $(this).val(""); $(this).css("color","#4c4c4c"); } }); /* Onblur, if empty, insert defaultvalue */ $(this).blur(function(){ alert("ud"); if($(this).val() == "") { $(this).val($(this).attr("defaultvalue")); $(this).css("color","#9d9d9d"); }else { $(this).removeClass("ignore"); } }); } }); I use this code to insert some default text into some of my input fields, when nothing else is typed in. This means that when a user sees my search-form, the defaultvalues will be set as an attribute on the input-field, and this will be the value that is shown. When a user clicks inside of the input field, the default value will be removed. When the user sees an input field at first is looks like this: <input type="text" value="" defaultvalue="From" /> This works just fine, but I have a big challenge. If a user have posted the form, and something is entered into one of the fields, then I can't show the default value in the field, if the user deletes the text from the input field. This is happening because the value of the text-field is still containing something, even when the user deletes the content. So my problem is how to show the default value when the form is submitted, and the user then removes the typed in content? When the form is submitted the input looks like this, and keeps looking like this until the form is submitted again: <input type="text" value="someValue" defaultvalue="From" /> So I need to show the default value in the input-field right after the user have deleted the content in the field, and removed the focus from the field. Does everyone understand what my problem is? Otherwise just ask, I have struggled with this one for quite some times now, so any help will be greatly appreciated. Thanks in advance, Kim Andersen

    Read the article

  • Problem with custom paging in ASP.NET

    - by JohnCC
    I'm trying to add custom paging to my site using the ObjectDataSource paging. I believe I've correctly added the stored procedures I need, and brought them up through the DAL and BLL. The problem I have is that when I try to use it on a page, I get an empty datagrid. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageTest.aspx.cs" Inherits="developer_PageTest" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:ObjectDataSource ID="ObjectDataSource1" SelectMethod="GetMessagesPaged" EnablePaging="true" SelectCountMethod="GetMessagesCount" TypeName="MessageTable" runat="server" > <SelectParameters> <asp:Parameter Name="DeviceID" Type="Int32" DefaultValue="112" /> <asp:Parameter Name="StartDate" Type="DateTime" DefaultValue="" ConvertEmptyStringToNull="true"/> <asp:Parameter Name="EndDate" Type="DateTime" DefaultValue="" ConvertEmptyStringToNull="true"/> <asp:Parameter Name="BasicMatch" Type="Boolean" ConvertEmptyStringToNull="true" DefaultValue="" /> <asp:Parameter Name="ContainsPosition" Type="Boolean" ConvertEmptyStringToNull="true" DefaultValue="" /> <asp:Parameter Name="Decoded" Type="Boolean" ConvertEmptyStringToNull="true" DefaultValue="" /> <%-- <asp:Parameter Name="StartRowIndex" Type="Int32" DefaultValue="10" /> <asp:Parameter Name="MaximumRows" Type="Int32" DefaultValue="10" /> --%> </SelectParameters> </asp:ObjectDataSource> <asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1" AllowPaging="true" PageSize="10"></asp:GridView> <br /> <asp:Label runat="server" ID="lblCount"></asp:Label> </div> </form> </body> </html> When I set EnablePaging to false on the ODS, and add the commented out StartRowIndex and MaximumRows params in the markup, I get data so it really seems like the data layer is behaving as it should. There's code in code file to put the value of the GetMessagesCount call in the lblCount, and that always has a sensible value in it. I've tried breaking in the BLL and stepping through, and the backend is getting called, and it is returning what looks like the right information and data, but somehow between the ODS and the GridView it's vanishing. I created a mock data source which returned numbered rows of random numbers and attached it to this form, and the custom paging worked so I think my understanding of the technique is good. I just can't see why it fails here! Any help really appreciated. (EDIT .. here's the code behind). using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.ComponentModel; public partial class developer_PageTest : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lblCount.Text = String.Format("Count = {0}", MessageTable.GetMessagesCount(112, null, null, null, null, null)) } }

    Read the article

  • How can I validate the result in an ASP.NET MVC editor template?

    - by Morten Christiansen
    I have created an editor template for representing selecting from a dynamic dropdown list and it works as it should except for validation, which I have been unable to figure out. If the model has the [Required] attribute set, I want that to invalidate if the default option is selected. The view model object that must be represented as the dropdown list is Selector: public class Selector { public int SelectedId { get; set; } public IEnumerable<Pair<int, string>> Choices { get; private set; } public string DefaultValue { get; set; } public Selector() { //For binding the object on Post } public Selector(IEnumerable<Pair<int, string>> choices, string defaultValue) { DefaultValue = defaultValue; Choices = choices; } } The editor template looks like this: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <select class="template-selector" id="<%= ViewData.ModelMetadata.PropertyName %>.SelectedId" name="<%= ViewData.ModelMetadata.PropertyName %>.SelectedId"> <% var model = ViewData.ModelMetadata.Model as QASW.Web.Mvc.Selector; if (model != null) { %> <option><%= model.DefaultValue %></option><% foreach (var choice in model.Choices) { %> <option value="<%= choice.Value1 %>"><%= choice.Value2 %></option><% } } %> </select> I sort of got it to work by calling it from the view like this (where Category is a Selector): <%= Html.ValidationMessageFor(n => n.Category.SelectedId)%> But it shows the validation error for not supplying a proper number and it does not care if I set the Required attribute.

    Read the article

  • Can't set LinqDataSource InsertParameters from my code behind.

    - by Abe Miessler
    I have the following code that seems like it should set my insertParameter but everytime an insert happens it uses the default parameter. Do i need to do anything special to make this work? Codebehind: protected void SetInsertParams(object sender, LinqDataSourceInsertEventArgs e) { if (lbl_Personnel.Visible) { lds_Personnel.InsertParameters["BudgetLineTypeCode"].DefaultValue = "S"; } else if(lbl_Operating.Visible) { lds_Personnel.InsertParameters["BudgetLineTypeCode"].DefaultValue = "O"; } else if (lbl_SubContractor.Visible) { lds_Personnel.InsertParameters["BudgetLineTypeCode"].DefaultValue = "C"; } } From my aspx page: <asp:LinqDataSource ID="lds_Personnel" runat="server" OnSelecting="SetParams" ContextTypeName="nrm.FRGPproposal.FrgpropDataContext" TableName="BudgetLines" OnInserted="lds_Personnel_OnInserted" OnInserting="SetInsertParams" Where="ProposalID == @PropNumber &amp;&amp; BudgetLineTypeCode == @BudgetLineTypeCode" EnableDelete="True" EnableInsert="True" EnableUpdate="True"> <WhereParameters> <asp:SessionParameter Name="PropNumber" SessionField="PropNumber" Type="Int32" /> <asp:Parameter DefaultValue="S" Name="BudgetLineTypeCode" Type="Char" /> </WhereParameters> <InsertParameters> <asp:SessionParameter Name="ProposalID" SessionField="PropNumber" Type="Int32"/> <asp:Parameter DefaultValue="S" Name="BudgetLineTypeCode" Type="Char" /> </InsertParameters> </asp:LinqDataSource>

    Read the article

  • How do I get query string value from script path?

    - by TruMan1
    I am adding my Javsacript file in pages with different query strings in the script path like this: Page1: <script type="text/javascript" src="file.js?abc=123"></script> Page2: <script type="text/javascript" src="file.js?abc=456"></script> Page3: <script type="text/javascript" src="file.js?abc=789"></script> In my Javascript file, how can I get the value of the "abc" param? I tried using window.location for this, but that does not work. In case it helps, below is a function I use to find the value of a query string param: function getQuerystring(key, defaultValue) { if (defaultValue == null) defaultValue = ""; key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regex = new RegExp("[\\?&]" + key + "=([^&#]*)"); var qs = regex.exec(window.location.href); if (qs == null) return defaultValue; else return qs[1]; }

    Read the article

  • How do I cast from int to generic type Integer?

    - by Rob Kent
    I'm relatively new to Java and am used to generics in C# so have struggled a bit with this code. Basically I want a generic method for getting a stored Android preference by key and this code, albeit ugly, works for a Boolean but not an Integer, when it blows up with a ClassCastException. Can anyone tell me why this is wrong and maybe help me improve the whole routine (using wildcards?)? public static <T> T getPreference(Class<T> argType, String prefKey, T defaultValue, SharedPreferences sharedPreferences) { ... try { if (argType == Boolean.class) { Boolean def = (Boolean) defaultValue; return argType.cast(sharedPreferences.getBoolean(prefKey, def)); } else if (argType == Integer.class) { Integer def = (Integer) defaultValue; return argType.cast(sharedPreferences.getInt(prefKey, def)); } else { AppGlobal.logWarning("getPreference: Unknown type '%s' for preference '%s'. Returning default value.", argType.getName(), prefKey); return defaultValue; } } catch (ClassCastException e) { AppGlobal.logError("Cast exception when reading pref %s. Using default value.", prefKey); return defaultValue; } } I've tried various ways - using the native int, casting to an Integer, but nothing works.

    Read the article

  • F# Simple Twitter Update

    - by mroberts
    A short while ago I posted some code for a C# twitter update.  I decided to move the same functionality / logic to F#.  Here is what I came up with. 1: namespace Server.Actions 2:   3: open System 4: open System.IO 5: open System.Net 6: open System.Text 7:   8: type public TwitterUpdate() = 9: 10: //member variables 11: [<DefaultValue>] val mutable _body : string 12: [<DefaultValue>] val mutable _userName : string 13: [<DefaultValue>] val mutable _password : string 14:   15: //Properties 16: member this.Body with get() = this._body and set(value) = this._body <- value 17: member this.UserName with get() = this._userName and set(value) = this._userName <- value 18: member this.Password with get() = this._password and set(value) = this._password <- value 19:   20: //Methods 21: member this.Execute() = 22: let login = String.Format("{0}:{1}", this._userName, this._password) 23: let creds = Convert.ToBase64String(Encoding.ASCII.GetBytes(login)) 24: let tweet = Encoding.ASCII.GetBytes(String.Format("status={0}", this._body)) 25: let request = WebRequest.Create("http://twitter.com/statuses/update.xml") :?> HttpWebRequest 26: 27: request.Method <- "POST" 28: request.ServicePoint.Expect100Continue <- false 29: request.Headers.Add("Authorization", String.Format("Basic {0}", creds)) 30: request.ContentType <- "application/x-www-form-urlencoded" 31: request.ContentLength <- int64 tweet.Length 32: 33: let reqStream = request.GetRequestStream() 34: reqStream.Write(tweet, 0, tweet.Length) 35: reqStream.Close() 36:   37: let response = request.GetResponse() :?> HttpWebResponse 38:   39: match response.StatusCode with 40: | HttpStatusCode.OK -> true 41: | _ -> false   While the above seems to work, it feels to me like it is not taking advantage of some functional concepts.  Love to get some feedback as to how to make the above more “functional” in nature.  For example, I don’t like the mutable properties.

    Read the article

  • how to change a button into a imagebutton in asp.net c#

    - by sweetsecret
    How to change the button into image button... the button in the beginning has "Pick a date" when clicked a calender pops out and the when a date is selected a label at the bottom reading the date comes in and the text on the button changes to disabled... i want to palce a imagebutton having a image icon of the calender and rest of the function will be the same.... the code as follows: using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; [assembly: TagPrefix("DatePicker", "EWS")] namespace EclipseWebSolutions.DatePicker { [DefaultProperty("Text")] [ToolboxData("<{0}:DatePicker runat=server")] [DefaultEvent("SelectionChanged")] [ValidationProperty("TextValue")] public class DatePicker : WebControl, INamingContainer { #region Properties public TextBox txtDate = new TextBox(); public Calendar calDate = new Calendar(); public Button btnDate = new Button(); public Panel pnlCalendar = new Panel(); private enum ViewStateConstants { ValidationGroup, RegularExpression, ErrorMessage, RegExText, CalendarPosition, FormatString, ExpandLabel, CollapseLabel, ApplyDefaultStyle, CausesValidation, } /// <summary> /// Defines the available display modes of this calendar. /// </summary> public enum CalendarDisplay { DisplayRight, DisplayBelow } /// <summary> /// Where to display the popup calendar. /// </summary> [Category("Behaviour")] [Localizable(true)] public CalendarDisplay CalendarPosition { get { if (ViewState[ViewStateConstants.CalendarPosition.ToString()] == null) { ViewState[ViewStateConstants.CalendarPosition.ToString()] = CalendarDisplay.DisplayRight; } return (CalendarDisplay)ViewState[ViewStateConstants.CalendarPosition.ToString()]; } set { ViewState[ViewStateConstants.CalendarPosition.ToString()] = value; } } /// <summary> /// Text version of the control's value, for use by ASP.NET validators. /// </summary> public string TextValue { get { return txtDate.Text; } } /// <summary> /// Holds the current date value of this control. /// </summary> [Category("Behaviour")] [Localizable(true)] [Bindable(true, BindingDirection.TwoWay)] public DateTime DateValue { get { try { if (txtDate.Text == "") return DateTime.MinValue; DateTime val = DateTime.Parse(txtDate.Text); return val; } catch (ArgumentNullException) { return DateTime.MinValue; } catch (FormatException) { return DateTime.MinValue; } } set { if (value == DateTime.MinValue) { txtDate.Text = ""; } else { txtDate.Text = value.ToShortDateString(); } } } [Category("Behavior"), Themeable(false), DefaultValue("")] public virtual string ValidationGroup { get { if (ViewState[ViewStateConstants.ValidationGroup.ToString()] == null) { return string.Empty; } else { return (string)ViewState[ViewStateConstants.ValidationGroup.ToString()]; } } set { ViewState[ViewStateConstants.ValidationGroup.ToString()] = value; } } /// <summary> /// The label of the exand button. Shown when the calendar is hidden. /// </summary> [Bindable(true)] [Category("Appearance")] [DefaultValue("PickDate")] [Localizable(true)] public string ExpandButtonLabel { get { String s = (String)ViewState[ViewStateConstants.ExpandLabel.ToString()]; return ((s == null) ? "PickDate" : s); } set { ViewState[ViewStateConstants.ExpandLabel.ToString()] = value; } } /// <summary> /// The label of the collapse button. Shown when the calendar is visible. /// </summary> [Bindable(true)] [Category("Appearance")] [DefaultValue("Disabled")] [Localizable(true)] public string CollapseButtonLabel { get { String s = (String)ViewState[ViewStateConstants.CollapseLabel.ToString()]; return ((s == null) ? "Disabled" : s); } set { ViewState[ViewStateConstants.CollapseLabel.ToString()] = value; } } /// <summary> /// Whether to apply the default style. Disable this if you want to apply a custom style, or to use themes and skins /// to style the control. /// </summary> [Category("Appearance")] [DefaultValue(true)] [Localizable(true)] public bool ApplyDefaultStyle { get { if (ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] == null) { ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] = true; } return (bool)ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()]; } set { ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] = value; } } /// <summary> /// Causes Validation /// </summary> [Category("Appearance")] [DefaultValue(false)] [Localizable(false)] public bool CausesValidation { get { if (ViewState[ViewStateConstants.CausesValidation.ToString()] == null) { ViewState[ViewStateConstants.CausesValidation.ToString()] = false; } return (bool)ViewState[ViewStateConstants.CausesValidation.ToString()]; } set { ViewState[ViewStateConstants.CausesValidation.ToString()] = value; btnDate.CausesValidation = value; } } #endregion #region Events /// <summary> /// A day was selected from the calendar control. /// </summary> public event EventHandler SelectionChanged; protected virtual void OnSelectionChanged() { if (SelectionChanged != null) // only raise the event if someone is listening. { SelectionChanged(this, EventArgs.Empty); } } #endregion #region Event Handlers /// <summary> /// The +/- button was clicked. /// </summary> protected void btnDate_Click(object sender, System.EventArgs e) { if (!calDate.Visible) { // expand the calendar calDate.Visible = true; txtDate.Enabled = false; btnDate.Text = CollapseButtonLabel; if (DateValue != DateTime.MinValue) { calDate.SelectedDate = DateValue; calDate.VisibleDate = DateValue; } } else { // collapse the calendar calDate.Visible = false; txtDate.Enabled = true; btnDate.Text = ExpandButtonLabel; } } /// <summary> /// A date was selected from the calendar. /// </summary> protected void calDate_SelectionChanged(object sender, System.EventArgs e) { calDate.Visible = false; txtDate.Visible = true; btnDate.Text = ExpandButtonLabel; txtDate.Enabled = true; txtDate.Text = calDate.SelectedDate.ToShortDateString(); OnSelectionChanged(); } #endregion /// <summary> /// Builds the contents of this control. /// </summary> protected override void CreateChildControls() { btnDate.Text = ExpandButtonLabel; btnDate.CausesValidation = CausesValidation; txtDate.ID = "txtDate"; calDate.Visible = false; if (ApplyDefaultStyle) { calDate.BackColor = System.Drawing.Color.White; calDate.BorderColor = System.Drawing.Color.FromArgb(10066329); calDate.CellPadding = 2; calDate.DayNameFormat = DayNameFormat.Shortest; calDate.Font.Name = "Verdana"; calDate.Font.Size = FontUnit.Parse("8pt"); calDate.ForeColor = System.Drawing.Color.Black; calDate.Height = new Unit(150, UnitType.Pixel); calDate.Width = new Unit(180, UnitType.Pixel); calDate.DayHeaderStyle.BackColor = System.Drawing.Color.FromArgb(228, 228, 228); calDate.DayHeaderStyle.Font.Size = FontUnit.Parse("7pt"); calDate.TitleStyle.Font.Bold = true; calDate.WeekendDayStyle.BackColor = System.Drawing.Color.FromArgb(255, 255, 204); } ConnectEventHandlers(); pnlCalendar.Controls.Add(calDate); pnlCalendar.Style["position"] = "absolute"; pnlCalendar.Style["filter"] = "alpha(opacity=95)"; pnlCalendar.Style["-moz-opacity"] = ".95"; pnlCalendar.Style["opacity"] = ".95"; pnlCalendar.Style["z-index"] = "2"; pnlCalendar.Style["background-color"] = "White"; if (CalendarPosition == CalendarDisplay.DisplayBelow) { pnlCalendar.Style["margin-top"] = "27px"; } else { pnlCalendar.Style["display"] = "inline"; } Controls.Add(txtDate); Controls.Add(pnlCalendar); Controls.Add(btnDate); base.CreateChildControls(); } /// <summary> /// Render the contents of this control. /// </summary> /// <param name="output">The HtmlTextWriter to use.</param> protected override void RenderContents(HtmlTextWriter output) { switch (CalendarPosition) { case CalendarDisplay.DisplayRight: { txtDate.RenderControl(output); btnDate.RenderControl(output); pnlCalendar.RenderControl(output); break; } case CalendarDisplay.DisplayBelow: { pnlCalendar.RenderControl(output); txtDate.RenderControl(output); btnDate.RenderControl(output); break; } } } /// <summary> /// Connect event handlers to events. /// </summary> private void ConnectEventHandlers() { btnDate.Click += new System.EventHandler(btnDate_Click); calDate.SelectionChanged += new System.EventHandler(calDate_SelectionChanged); } } } using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; [assembly: TagPrefix("DatePicker", "EWS")] namespace EclipseWebSolutions.DatePicker { [DefaultProperty("Text")] [ToolboxData("<{0}:DatePicker runat=server")] [DefaultEvent("SelectionChanged")] [ValidationProperty("TextValue")] public class DatePicker : WebControl, INamingContainer { #region Properties public TextBox txtDate = new TextBox(); public Calendar calDate = new Calendar(); public Button btnDate = new Button(); public Panel pnlCalendar = new Panel(); private enum ViewStateConstants { ValidationGroup, RegularExpression, ErrorMessage, RegExText, CalendarPosition, FormatString, ExpandLabel, CollapseLabel, ApplyDefaultStyle, CausesValidation, } /// <summary> /// Defines the available display modes of this calendar. /// </summary> public enum CalendarDisplay { DisplayRight, DisplayBelow } /// <summary> /// Where to display the popup calendar. /// </summary> [Category("Behaviour")] [Localizable(true)] public CalendarDisplay CalendarPosition { get { if (ViewState[ViewStateConstants.CalendarPosition.ToString()] == null) { ViewState[ViewStateConstants.CalendarPosition.ToString()] = CalendarDisplay.DisplayRight; } return (CalendarDisplay)ViewState[ViewStateConstants.CalendarPosition.ToString()]; } set { ViewState[ViewStateConstants.CalendarPosition.ToString()] = value; } } /// <summary> /// Text version of the control's value, for use by ASP.NET validators. /// </summary> public string TextValue { get { return txtDate.Text; } } /// <summary> /// Holds the current date value of this control. /// </summary> [Category("Behaviour")] [Localizable(true)] [Bindable(true, BindingDirection.TwoWay)] public DateTime DateValue { get { try { if (txtDate.Text == "") return DateTime.MinValue; DateTime val = DateTime.Parse(txtDate.Text); return val; } catch (ArgumentNullException) { return DateTime.MinValue; } catch (FormatException) { return DateTime.MinValue; } } set { if (value == DateTime.MinValue) { txtDate.Text = ""; } else { txtDate.Text = value.ToShortDateString(); } } } [Category("Behavior"), Themeable(false), DefaultValue("")] public virtual string ValidationGroup { get { if (ViewState[ViewStateConstants.ValidationGroup.ToString()] == null) { return string.Empty; } else { return (string)ViewState[ViewStateConstants.ValidationGroup.ToString()]; } } set { ViewState[ViewStateConstants.ValidationGroup.ToString()] = value; } } /// <summary> /// The label of the exand button. Shown when the calendar is hidden. /// </summary> [Bindable(true)] [Category("Appearance")] [DefaultValue("PickDate")] [Localizable(true)] public string ExpandButtonLabel { get { String s = (String)ViewState[ViewStateConstants.ExpandLabel.ToString()]; return ((s == null) ? "PickDate" : s); } set { ViewState[ViewStateConstants.ExpandLabel.ToString()] = value; } } /// <summary> /// The label of the collapse button. Shown when the calendar is visible. /// </summary> [Bindable(true)] [Category("Appearance")] [DefaultValue("Disabled")] [Localizable(true)] public string CollapseButtonLabel { get { String s = (String)ViewState[ViewStateConstants.CollapseLabel.ToString()]; return ((s == null) ? "Disabled" : s); } set { ViewState[ViewStateConstants.CollapseLabel.ToString()] = value; } } /// <summary> /// Whether to apply the default style. Disable this if you want to apply a custom style, or to use themes and skins /// to style the control. /// </summary> [Category("Appearance")] [DefaultValue(true)] [Localizable(true)] public bool ApplyDefaultStyle { get { if (ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] == null) { ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] = true; } return (bool)ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()]; } set { ViewState[ViewStateConstants.ApplyDefaultStyle.ToString()] = value; } } /// <summary> /// Causes Validation /// </summary> [Category("Appearance")] [DefaultValue(false)] [Localizable(false)] public bool CausesValidation { get { if (ViewState[ViewStateConstants.CausesValidation.ToString()] == null) { ViewState[ViewStateConstants.CausesValidation.ToString()] = false; } return (bool)ViewState[ViewStateConstants.CausesValidation.ToString()]; } set { ViewState[ViewStateConstants.CausesValidation.ToString()] = value; btnDate.CausesValidation = value; } } #endregion #region Events /// <summary> /// A day was selected from the calendar control. /// </summary> public event EventHandler SelectionChanged; protected virtual void OnSelectionChanged() { if (SelectionChanged != null) // only raise the event if someone is listening. { SelectionChanged(this, EventArgs.Empty); } } #endregion #region Event Handlers /// <summary> /// The +/- button was clicked. /// </summary> protected void btnDate_Click(object sender, System.EventArgs e) { if (!calDate.Visible) { // expand the calendar calDate.Visible = true; txtDate.Enabled = false; btnDate.Text = CollapseButtonLabel; if (DateValue != DateTime.MinValue) { calDate.SelectedDate = DateValue; calDate.VisibleDate = DateValue; } } else { // collapse the calendar calDate.Visible = false; txtDate.Enabled = true; btnDate.Text = ExpandButtonLabel; } } /// <summary> /// A date was selected from the calendar. /// </summary> protected void calDate_SelectionChanged(object sender, System.EventArgs e) { calDate.Visible = false; txtDate.Visible = true; btnDate.Text = ExpandButtonLabel; txtDate.Enabled = true; txtDate.Text = calDate.SelectedDate.ToShortDateString(); OnSelectionChanged(); } #endregion /// <summary> /// Builds the contents of this control. /// </summary> protected override void CreateChildControls() { btnDate.Text = ExpandButtonLabel; btnDate.CausesValidation = CausesValidation; txtDate.ID = "txtDate"; calDate.Visible = false; if (ApplyDefaultStyle) { calDate.BackColor = System.Drawing.Color.White; calDate.BorderColor = System.Drawing.Color.FromArgb(10066329); calDate.CellPadding = 2; calDate.DayNameFormat = DayNameFormat.Shortest; calDate.Font.Name = "Verdana"; calDate.Font.Size = FontUnit.Parse("8pt"); calDate.ForeColor = System.Drawing.Color.Black; calDate.Height = new Unit(150, UnitType.Pixel); calDate.Width = new Unit(180, UnitType.Pixel); calDate.DayHeaderStyle.BackColor = System.Drawing.Color.FromArgb(228, 228, 228); calDate.DayHeaderStyle.Font.Size = FontUnit.Parse("7pt"); calDate.TitleStyle.Font.Bold = true; calDate.WeekendDayStyle.BackColor = System.Drawing.Color.FromArgb(255, 255, 204); } ConnectEventHandlers(); pnlCalendar.Controls.Add(calDate); pnlCalendar.Style["position"] = "absolute"; pnlCalendar.Style["filter"] = "alpha(opacity=95)"; pnlCalendar.Style["-moz-opacity"] = ".95"; pnlCalendar.Style["opacity"] = ".95"; pnlCalendar.Style["z-index"] = "2"; pnlCalendar.Style["background-color"] = "White"; if (CalendarPosition == CalendarDisplay.DisplayBelow) { pnlCalendar.Style["margin-top"] = "27px"; } else { pnlCalendar.Style["display"] = "inline"; } Controls.Add(txtDate); Controls.Add(pnlCalendar); Controls.Add(btnDate); base.CreateChildControls(); } /// <summary> /// Render the contents of this control. /// </summary> /// <param name="output">The HtmlTextWriter to use.</param> protected override void RenderContents(HtmlTextWriter output) { switch (CalendarPosition) { case CalendarDisplay.DisplayRight: { txtDate.RenderControl(output); btnDate.RenderControl(output); pnlCalendar.RenderControl(output); break; } case CalendarDisplay.DisplayBelow: { pnlCalendar.RenderControl(output); txtDate.RenderControl(output); btnDate.RenderControl(output); break; } } } /// <summary> /// Connect event handlers to events. /// </summary> private void ConnectEventHandlers() { btnDate.Click += new System.EventHandler(btnDate_Click); calDate.SelectionChanged += new System.EventHandler(calDate_SelectionChanged); } } } <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" % <%@ Register Assembly="EclipseWebSolutions.DatePicker" Namespace="EclipseWebSolutions.DatePicker" TagPrefix="ews" % Untitled Page       using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void DatePicker1_SelectionChanged(object sender, EventArgs e) { Label1.Text = DatePicker1.DateValue.ToShortDateString(); pnlLabel.Update(); } }

    Read the article

  • Missing Fields and Default Values

    - by PointsToShare
    © 2011 By: Dov Trietsch. All rights reserved Dealing with Missing Fields and Default Values New fields and new default values are not propagated throughout the list. They only apply to new and updated items and not to items already entered. They are only prospective. We need to be able to deal with this issue. Here is a scenario. The user has an old list with old items and adds a new field. The field is not created for any of the old items. Trying to get its value raises an Argument Exception. Here is another: a default value is added to a field. All the old items, where the field was not assigned a value, do not get the new default value. The two can also happen in tandem – a new field is added with a default. The older items have neither. Even better, if the user changes the default value, the old items still carry the old defaults. Let’s go a bit further. You have already written code for the list, be it an event receiver, a feature receiver, a console app or a command extension, in which you span all the fields and run on selected items – some new (no problem) and some old (problems aplenty). Had you written defensive code, you would be able to handle the situation, including similar changes in the future. So, without further ado, here’s how. Instead of just getting the value of a field in an item – item[field].ToString() – use the function below. I use ItemValue(item, fieldname, “mud in your eye”) and if “mud in your eye” is what I get, I know that the item did not have the field.   /// <summary> /// Return the column value or a default value /// </summary> private static string ItemValue(SPItem item, string column, string defaultValue) {     try     {         return item[column].ToString();     }     catch (NullReferenceException ex)     {         return defaultValue;     }     catch (ArgumentException ex)     {         return defaultValue;     } } I also use a similar function to return the default and a funny default-default to ascertain that the default does not exist. Here it is:  /// <summary> /// return a fields default or the "default" default. /// </summary> public static string GetFieldDefault(SPField fld, string defValue) {     try     {         // -- Check if default exists.         return fld.DefaultValue.ToString();     }     catch (NullReferenceException ex)     {         return defValue;     }     catch (ArgumentException ex)     {         return defValue;     } } How is this defensive? You have trapped an expected error and dealt with it. Therefore the program did not stop cold in its track and the required code ran to its end. Now, take a further step - write to a log (See Logging – a log blog). Read your own log every now and then, and act accordingly. That’s all Folks!

    Read the article

  • Android App Crashes On Second Run

    - by user1091286
    My app runs fine on first run. On the Menu I added two choices options and quit. options which set up a new intent who goes to a PreferenceActivity and quit which simply call: "android.os.Process.killProcess(android.os.Process.myPid());" On the second time I run my app (after I quit from inside the emulator) it crashes.. Ideas? the menu is called by the foolowing code: @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu , menu); return true; } - @Override public boolean onOptionsItemSelected(MenuItem item) { // Set up a new intent between the updater service and the main screen Intent options = new Intent(this, OptionsScreenActivity.class); // Switch case on the options switch (item.getItemId()) { case R.id.options: startActivity(options); return true; case R.id.quit: android.os.Process.killProcess(android.os.Process.myPid()); return true; default: return false; } Code for SeekBarPreference: package com.testapp.logic; import com.testapp.R; import android.content.Context; import android.content.res.TypedArray; import android.preference.Preference; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; public class SeekBarPreference extends Preference implements OnSeekBarChangeListener { private final String TAG = getClass().getName(); private static final String ANDROIDNS="http://schemas.android.com/apk/res/android"; private static final String PREFS="com.testapp.logic"; private static final int DEFAULT_VALUE = 5; private int mMaxValue = 100; private int mMinValue = 1; private int mInterval = 1; private int mCurrentValue; private String mUnitsLeft = ""; private String mUnitsRight = ""; private SeekBar mSeekBar; private TextView mStatusText; public SeekBarPreference(Context context, AttributeSet attrs) { super(context, attrs); initPreference(context, attrs); } public SeekBarPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initPreference(context, attrs); } private void initPreference(Context context, AttributeSet attrs) { setValuesFromXml(attrs); mSeekBar = new SeekBar(context, attrs); mSeekBar.setMax(mMaxValue - mMinValue); mSeekBar.setOnSeekBarChangeListener(this); } private void setValuesFromXml(AttributeSet attrs) { mMaxValue = attrs.getAttributeIntValue(ANDROIDNS, "max", 100); mMinValue = attrs.getAttributeIntValue(PREFS, "min", 0); mUnitsLeft = getAttributeStringValue(attrs, PREFS, "unitsLeft", ""); String units = getAttributeStringValue(attrs, PREFS, "units", ""); mUnitsRight = getAttributeStringValue(attrs, PREFS, "unitsRight", units); try { String newInterval = attrs.getAttributeValue(PREFS, "interval"); if(newInterval != null) mInterval = Integer.parseInt(newInterval); } catch(Exception e) { Log.e(TAG, "Invalid interval value", e); } } private String getAttributeStringValue(AttributeSet attrs, String namespace, String name, String defaultValue) { String value = attrs.getAttributeValue(namespace, name); if(value == null) value = defaultValue; return value; } @Override protected View onCreateView(ViewGroup parent){ RelativeLayout layout = null; try { LayoutInflater mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); layout = (RelativeLayout)mInflater.inflate(R.layout.seek_bar_preference, parent, false); } catch(Exception e) { Log.e(TAG, "Error creating seek bar preference", e); } return layout; } @Override public void onBindView(View view) { super.onBindView(view); try { // move our seekbar to the new view we've been given ViewParent oldContainer = mSeekBar.getParent(); ViewGroup newContainer = (ViewGroup) view.findViewById(R.id.seekBarPrefBarContainer); if (oldContainer != newContainer) { // remove the seekbar from the old view if (oldContainer != null) { ((ViewGroup) oldContainer).removeView(mSeekBar); } // remove the existing seekbar (there may not be one) and add ours newContainer.removeAllViews(); newContainer.addView(mSeekBar, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } } catch(Exception ex) { Log.e(TAG, "Error binding view: " + ex.toString()); } updateView(view); } /** * Update a SeekBarPreference view with our current state * @param view */ protected void updateView(View view) { try { RelativeLayout layout = (RelativeLayout)view; mStatusText = (TextView)layout.findViewById(R.id.seekBarPrefValue); mStatusText.setText(String.valueOf(mCurrentValue)); mStatusText.setMinimumWidth(30); mSeekBar.setProgress(mCurrentValue - mMinValue); TextView unitsRight = (TextView)layout.findViewById(R.id.seekBarPrefUnitsRight); unitsRight.setText(mUnitsRight); TextView unitsLeft = (TextView)layout.findViewById(R.id.seekBarPrefUnitsLeft); unitsLeft.setText(mUnitsLeft); } catch(Exception e) { Log.e(TAG, "Error updating seek bar preference", e); } } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int newValue = progress + mMinValue; if(newValue > mMaxValue) newValue = mMaxValue; else if(newValue < mMinValue) newValue = mMinValue; else if(mInterval != 1 && newValue % mInterval != 0) newValue = Math.round(((float)newValue)/mInterval)*mInterval; // change rejected, revert to the previous value if(!callChangeListener(newValue)){ seekBar.setProgress(mCurrentValue - mMinValue); return; } // change accepted, store it mCurrentValue = newValue; mStatusText.setText(String.valueOf(newValue)); persistInt(newValue); } public void onStartTrackingTouch(SeekBar seekBar) {} public void onStopTrackingTouch(SeekBar seekBar) { notifyChanged(); } @Override protected Object onGetDefaultValue(TypedArray ta, int index){ int defaultValue = ta.getInt(index, DEFAULT_VALUE); return defaultValue; } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { if(restoreValue) { mCurrentValue = getPersistedInt(mCurrentValue); } else { int temp = 0; try { temp = (Integer)defaultValue; } catch(Exception ex) { Log.e(TAG, "Invalid default value: " + defaultValue.toString()); } persistInt(temp); mCurrentValue = temp; } } } Logcat: E/AndroidRuntime( 4525): FATAL EXCEPTION: main E/AndroidRuntime( 4525): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.ui.testapp/com.logic.testapp.SeekBarPreferen ce}: java.lang.InstantiationException: can't instantiate class com.logic.testapp.SeekBarPreference; no empty constructor E/AndroidRuntime( 4525): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1879) E/AndroidRuntime( 4525): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980) E/AndroidRuntime( 4525): at android.app.ActivityThread.access$600(ActivityThread.java:122) E/AndroidRuntime( 4525): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146) E/AndroidRuntime( 4525): at android.os.Handler.dispatchMessage(Handler.java:99) E/AndroidRuntime( 4525): at android.os.Looper.loop(Looper.java:137) E/AndroidRuntime( 4525): at android.app.ActivityThread.main(ActivityThread.java:4340) E/AndroidRuntime( 4525): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime( 4525): at java.lang.reflect.Method.invoke(Method.java:511) E/AndroidRuntime( 4525): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) E/AndroidRuntime( 4525): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) E/AndroidRuntime( 4525): at dalvik.system.NativeStart.main(Native Method) E/AndroidRuntime( 4525): Caused by: java.lang.InstantiationException: can't instantiate class com.logic.testapp.SeekBarPreference; no empty construc tor E/AndroidRuntime( 4525): at java.lang.Class.newInstanceImpl(Native Method) E/AndroidRuntime( 4525): at java.lang.Class.newInstance(Class.java:1319) E/AndroidRuntime( 4525): at android.app.Instrumentation.newActivity(Instrumentation.java:1023) E/AndroidRuntime( 4525): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1870) E/AndroidRuntime( 4525): ... 11 more W/ActivityManager( 84): Force finishing activity com.ui.testapp/com.logic.testapp.SeekBarPreference W/ActivityManager( 84): Force finishing activity com.ui.testapp/.MainScreen I/WindowManager( 84): createSurface Window{41a90320 paused=false}: DRAW NOW PENDING W/ActivityManager( 84): Activity pause timeout for ActivityRecord{4104a848 com.ui.testapp/com.logic.testapp.SeekBarPreference} W/NetworkManagementSocketTagger( 84): setKernelCountSet(10021, 1) failed with errno -2 I/WindowManager( 84): createSurface Window{412bcc10 com.android.launcher/com.android.launcher2.Launcher paused=false}: DRAW NOW PENDING W/NetworkManagementSocketTagger( 84): setKernelCountSet(10045, 0) failed with errno -2 I/Process ( 4525): Sending signal. PID: 4525 SIG: 9 I/ActivityManager( 84): Process com.ui.testapp (pid 4525) has died. I/WindowManager( 84): WIN DEATH: Window{41a6c9c0 com.ui.testapp/com.ui.testapp.MainScreen paused=true}

    Read the article

  • unrecognized selector sent to instance in xcode using objective c and sup as backend

    - by user1765037
    I am a beginner in native development.I made a project using xcode in objective C.It builded successfully.But when I run the project ,an error came like 'unrecognized selector sent to instance'.Why this is happening ?can anyone help me to solve this?I am attaching the error that I am getting with this.. And I am posting the code with this.... ConnectionController.m #import "ConnectionController.h" #import "SUPApplication.h" #import "Flight_DetailsFlightDB.h" #import "CallbackHandler.h" @interface ConnectionController() @property (nonatomic,retain)CallbackHandler *callbackhandler; @end @implementation ConnectionController @synthesize callbackhandler; static ConnectionController *appConnectionController; //Begin Application Setup +(void)beginApplicationSetup { if(!appConnectionController) { appConnectionController = [[[ConnectionController alloc]init]retain]; appConnectionController.callbackhandler = [[CallbackHandler getInstance]retain]; } if([SUPApplication connectionStatus] == SUPConnectionStatus_DISCONNECTED) [appConnectionController setupApplicationConnection]; else NSLog(@"Already Connected"); } -(BOOL)setupApplicationConnection { SUPApplication *app = [SUPApplication getInstance]; [app setApplicationIdentifier:@"HWC"]; [app setApplicationCallback:self.callbackhandler]; NSLog(@"inside setupApp"); SUPConnectionProperties *properties = [app connectionProperties]; NSLog(@"server"); [properties setServerName:@"sapecxxx.xxx.com"]; NSLog(@"inside setupAppser"); [properties setPortNumber:5001]; NSLog(@"inside setupApppot"); [properties setFarmId:@"0"]; NSLog(@"inside setupAppfarm"); [properties setUrlSuffix:@"/tm/?cid=%cid%"]; NSLog(@"inside setupAppurlsuff"); [properties setNetworkProtocol:@"http"]; SUPLoginCredentials *loginCred = [SUPLoginCredentials getInstance]; NSLog(@"inside setupAppmac"); [loginCred setUsername:@"mac"]; [loginCred setPassword:nil]; [properties setLoginCredentials:loginCred]; [properties setActivationCode:@"1234"]; if(![Flight_DetailsFlightDB databaseExists]) { [Flight_DetailsFlightDB createDatabase]; } SUPConnectionProfile *connprofile = [Flight_DetailsFlightDB getSynchronizationProfile]; [connprofile setNetworkProtocol:@"http"]; NSLog(@"inside setupAppPort2"); [connprofile setPortNumber:2480]; NSLog(@"inside setupAppser2"); [connprofile setServerName:@"sapecxxx.xxx.com"]; NSLog(@"inside setupAppdom2"); [connprofile setDomainName:@"Development"]; NSLog(@"inside setupAppuser"); [connprofile setUser:@"supAdmin"]; [connprofile setPassword:@"s3pAdmin"]; [connprofile setAsyncReplay:YES]; [connprofile setClientId:@"0"]; // [Flight_DetailsFlightDB beginOnlineLogin:@"supAdmin" password:@"s3pAdmin"]; [Flight_DetailsFlightDB registerCallbackHandler:self.callbackhandler]; [Flight_DetailsFlightDB setApplication:app]; if([SUPApplication connectionStatus] == SUPRegistrationStatus_REGISTERED) { [app startConnection:0]; } else { [app registerApplication:0]; } } @end ViewController.m #import "Demo_FlightsViewController.h" #import "ConnectionController.h" #import "Flight_DetailsFlightDB.h" #import "SUPObjectList.h" #import "Flight_DetailsSessionPersonalization.h" #import "Flight_DetailsFlight_MBO.h" #import "Flight_DetailsPersonalizationParameters.h" @interface Demo_FlightsViewController () @end @implementation Demo_FlightsViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } -(IBAction)Connect:(id)sender { @try { [ConnectionController beginApplicationSetup]; } @catch (NSException *exception) { NSLog(@"ConnectionAborted"); } // synchronise } -(IBAction)Synchronise:(id)sender { @try { [Flight_DetailsFlightDB synchronize]; NSLog(@"SYNCHRONISED"); } @catch (NSException *exception) { NSLog(@"Synchronisation Failed"); } } -(IBAction)findall:(id)sender { SUPObjectList *list = [Flight_DetailsSessionPersonalization findAll]; NSLog(@"no of lines got synchronised is %d",list.size); } -(IBAction)confirm:(id)sender { Flight_DetailsPersonalizationParameters *pp = [Flight_DetailsFlightDB getPersonalizationParameters]; MBOLogInfo(@"personalisation parmeter for airline id= %@",pp.Airline_PK); [pp setAirline_PK:@"AA"]; [pp save]; while([Flight_DetailsFlightDB hasPendingOperations]) { [NSThread sleepForTimeInterval:1]; } NSLog(@"inside confirm............"); [Flight_DetailsFlightDB beginSynchronize]; Flight_DetailsFlight_MBO *flight = nil; SUPObjectList *cl = nil; cl =[Flight_DetailsFlight_MBO findAll]; if(cl && cl.length > 0) { int i; for(i=0;i<cl.length;i++) { flight = [cl item:i]; if(flight) { NSLog(@"details are %@",flight.CITYFROM); } } } } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } @end SUPConnectionProfile.h #import "sybase_sup.h" #define FROM_IMPORT_THREAD TRUE #define FROM_APP_THREAD FALSE #define SUP_UL_MAX_CACHE_SIZE 10485760 @class SUPBooleanUtil; @class SUPNumberUtil; @class SUPStringList; @class SUPStringUtil; @class SUPPersistenceException; @class SUPLoginCertificate; @class SUPLoginCredentials; @class SUPConnectionProfile; /*! @class SUPConnectionProfile @abstract This class contains fields and methods needed to connect and authenticate to an SUP server. @discussion */ @interface SUPConnectionProfile : NSObject { SUPConnectionProfile* _syncProfile; SUPBoolean _threadLocal; SUPString _wrapperData; NSMutableDictionary* _delegate; SUPLoginCertificate* _certificate; SUPLoginCredentials* _credentials; int32_t _maxDbConnections; BOOL initTraceCalled; } /*! @method @abstract Return a new instance of SUPConnectionProfile. @discussion @result The SUPconnectionprofile object. */ + (SUPConnectionProfile*)getInstance; /*! @method @abstract Return a new instance of SUPConnectionProfile. @discussion This method is deprecated. use getInstance instead. @result The SUPconnectionprofile object. */ + (SUPConnectionProfile*)newInstance DEPRECATED_ATTRIBUTE NS_RETURNS_NON_RETAINED; - (SUPConnectionProfile*)init; /*! @property @abstract The sync profile. @discussion */ @property(readwrite, retain, nonatomic) SUPConnectionProfile* syncProfile; /*! @property @abstract The maximum number of active DB connections allowed @discussion Default value is 4, but can be changed by application developer. */ @property(readwrite, assign, nonatomic) int32_t maxDbConnections; /*! @method @abstract The SUPConnectionProfile manages an internal dictionary of key value pairs. This method returns the SUPString value for a given string. @discussion @param name The string. */ - (SUPString)getString:(SUPString)name; /*! @method @abstract The SUPConnectionProfile manages an internal dictionary of key value pairs. This method returns the SUPString value for a given string. If the value is not found, returns 'defaultValue'. @discussion @param name The string. @param defaultValue The default Value. */ - (SUPString)getStringWithDefault:(SUPString)name:(SUPString)defaultValue; /*! @method @abstract The SUPConnectionProfile manages an internal dictionary of key value pairs. This method returns the SUPBoolean value for a given string. @discussion @param name The string. */ - (SUPBoolean)getBoolean:(SUPString)name; /*! @method @abstract The SUPConnectionProfile manages an internal dictionary of key value pairs. This method returns the SUPBoolean value for a given string. If the value is not found, returns 'defaultValue'. @discussion @param name The string. @param defaultValue The default Value. */ - (SUPBoolean)getBooleanWithDefault:(SUPString)name:(SUPBoolean)defaultValue; /*! @method @abstract The SUPConnectionProfile manages an internal dictionary of key value pairs. This method returns the SUPInt value for a given string. @discussion @param name The string. */ - (SUPInt)getInt:(SUPString)name; /*! @method @abstract The SUPConnectionProfile manages an internal dictionary of key value pairs. This method returns the SUPInt value for a given string. If the value is not found, returns 'defaultValue'. @discussion @param name The string. @param defaultValue The default Value. */ - (SUPInt)getIntWithDefault:(SUPString)name:(SUPInt)defaultValue; /*! @method getUPA @abstract retrieve upa from profile @discussion if it is in profile's dictionary, it returns value for key "upa"; if it is not found in profile, it composes the upa value from base64 encoding of username:password; and also inserts it into profile's dictionary. @param none @result return string value of upa. */ - (SUPString)getUPA; /*! @method @abstract Sets the SUPString 'value' for the given 'name'. @discussion @param name The name. @param value The value. */ - (void)setString:(SUPString)name:(SUPString)value; /*! @method @abstract Sets the SUPBoolean 'value' for the given 'name'. @discussion @param name The name. @param value The value. */ - (void)setBoolean:(SUPString)name:(SUPBoolean)value; /*! @method @abstract Sets the SUPInt 'value' for the given 'name'. @discussion @param name The name. @param value The value. */ - (void)setInt:(SUPString)name:(SUPInt)value; /*! @method @abstract Sets the username. @discussion @param value The value. */ - (void)setUser:(SUPString)value; /*! @method @abstract Sets the password. @discussion @param value The value. */ - (void)setPassword:(SUPString)value; /*! @method @abstract Sets the ClientId. @discussion @param value The value. */ - (void)setClientId:(SUPString)value; /*! @method @abstract Returns the databasename. @discussion @param value The value. */ - (SUPString)databaseName; /*! @method @abstract Sets the databasename. @discussion @param value The value. */ - (void)setDatabaseName:(SUPString)value; @property(readwrite,copy, nonatomic) SUPString databaseName; /*! @method @abstract Gets the encryption key. @discussion @result The encryption key. */ - (SUPString)getEncryptionKey; /*! @method @abstract Sets the encryption key. @discussion @param value The value. */ - (void)setEncryptionKey:(SUPString)value; @property(readwrite,copy, nonatomic) SUPString encryptionKey; /*! @property @abstract The authentication credentials (username/password or certificate) for this profile. @discussion */ @property(retain,readwrite,nonatomic) SUPLoginCredentials *credentials; /*! @property @abstract The authentication certificate. @discussion If this is not null, certificate will be used for authentication. If this is null, credentials property (username/password) will be used. */ @property(readwrite,retain,nonatomic) SUPLoginCertificate *certificate; @property(readwrite, assign, nonatomic) BOOL initTraceCalled; /*! @method @abstract Gets the UltraLite collation creation parameter @discussion @result conllation string */ - (SUPString)getCollation; /*! @method @abstract Sets the UltraLite collation creation parameter @discussion @param value The value. */ - (void)setCollation:(SUPString)value; @property(readwrite,copy, nonatomic) SUPString collation; /*! @method @abstract Gets the maximum cache size in bytes; the default value for iOS is 10485760 (10 MB). @discussion @result max cache size */ - (int)getCacheSize; /*! @method @abstract Sets the maximum cache size in bytes. @discussion For Ultralite, passes the cache_max_size property into the connection parameters for DB connections; For SQLite, executes the "PRAGMA cache_size" statement when a connection is opened. @param cacheSize value */ - (void)setCacheSize:(int)cacheSize; @property(readwrite,assign, nonatomic) int cacheSize; /*! @method @abstract Returns the user. @discussion @result The username. */ - (SUPString)getUser; /*! @method @abstract Returns the password hash value. @discussion @result The password hash value. */ - (NSUInteger)getPasswordHash; /*! @method @abstract Returns the password. @discussion @result The password hash value. */ - (NSString*)getPassword; /*! @method @abstract Adds a new key value pair. @discussion @param key The key. @param value The value. */ - (void)add:(SUPString)key:(SUPString)value; /*! @method @abstract Removes the key. @discussion @param key The key to remove. */ - (void)remove:(SUPString)key; - (void)clear; /*! @method @abstract Returns a boolean indicating if the key is present. @discussion @param key The key. @result The result indicating if the key is present. */ - (SUPBoolean)containsKey:(SUPString)key; /*! @method @abstract Returns the item for the given key. @discussion @param key The key. @result The item. */ - (SUPString)item:(SUPString)key; /*! @method @abstract Returns the list of keys. @discussion @result The keylist. */ - (SUPStringList*)keys; /*! @method @abstract Returns the list of values. @discussion @result The value list. */ - (SUPStringList*)values; /*! @method @abstract Returns the internal map of key value pairs. @discussion @result The NSMutableDictionary with key value pairs. */ - (NSMutableDictionary*)internalMap; /*! @method @abstract Returns the domain name. @result The domain name. @discussion */ - (SUPString)getDomainName; /*! @method @abstract Sets the domain name. @param value The domain name. @discussion */ - (void)setDomainName:(SUPString)value; /*! @method @abstract Get async operation replay property. Default is true. @result YES : if ansync operation replay is enabled; NO: if async operation is disabled. @discussion */ - (BOOL) getAsyncReplay; /*! @method @abstract Set async operation replay property. Default is true. @result value: enable/disable async replay operation. @discussion */ - (void) setAsyncReplay:(BOOL) value; /*! @method @abstract enable or disable the trace in client object API. @param enable - YES: enable the trace; NO: disable the trace. @discussion */ - (void)enableTrace:(BOOL)enable; /*! @method @abstract enable or disable the trace with payload info in client object API. @param enable - YES: enable the trace; NO: disable the trace. @param withPayload = YES: show payload information; NO: not show payload information. @discussion */ - (void)enableTrace:(BOOL)enable withPayload:(BOOL)withPayload; /*! @method @abstract initialize trace levels from server configuration. @discussion */ - (void)initTrace; - (void)dealloc; /* ultralite/mobilink required parameters */ - (SUPString)getNetworkProtocol; - (void)setNetworkProtocol:(SUPString)protocol; - (SUPString)getNetworkStreamParams; - (void)setNetworkStreamParams:(SUPString)stream; - (SUPString)getServerName; - (void)setServerName:(SUPString)name; - (int)getPortNumber; - (void)setPortNumber:(int)port; - (int)getPageSize; - (void)setPageSize:(int)size; @end @interface SUPConnectionProfile(internal) - (void)applyPropertiesFromApplication; @end We are using SUP 2.1.3 library files.Please go through the code and help me...

    Read the article

  • autocomplete attribute is not passing XHTML 1.0 Transitional validation, why?

    - by rsturim
    I'm trying to cleanup my xhtml validation -- I'm running my pages through the W3C validator. For some puzzling reason it's not passing on input fields with the autocomplete="off" attribute: <input name="kwsearch" id="sli_search_1" type="text" autocomplete="off" onfocus="if(this.defaultValue==this.value) this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;" class="searchbox" value="Search" /> I'm using this doctype: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> And this is the validation error: Line 410, Column 81: there is no attribute "autocomplete" …li_search_1" type="text" autocomplete="off" onfocus="if(this.defaultValue==thi… I thought this was okay with the W3C -- but, maybe it's still in "submission" phase? http://www.w3.org/Submission/web-forms2/#autocomplete Thoughts?

    Read the article

  • Setting property default values for a Web User Control

    - by Jeremy Holland
    I am trying to build a web user control and set some default values for its properties in the code-behind like this: [DefaultValue(typeof(int), "50")] public int Height { get; set; } [DefaultValue(typeof(string), "string.Empty")] public string FamilyName { get; set; } [DefaultValue(typeof(Color), "Orange")] public System.Drawing.Color ForeColor { get; set; } When I add the user control to the page and call it without any properties: <uc1:Usercontrol ID="uc" runat="server" /> the default values are not set and every property is 0 or null. What am I doing wrong? Thanks.

    Read the article

  • How get an Android ListPreference defined in Xml whose values are integers?

    - by Rob Kent
    Is it possible to define a ListPreference in Xml and retrieve the value from SharedPreferences using getInt? Here is my Xml: <ListPreference android:key="@string/prefGestureAccuracyKey" android:title="@string/prefGestureAccuracyTitle" android:summary="@string/prefGestureAccuracyDesc" android:entries="@array/prefNumberAccuracyLabels" android:entryValues="@array/prefNumberAccuracyValues" android:dialogTitle="@string/prefGestureAccuracyDialog" android:persistent="true" android:defaultValue="2" android:shouldDisableView="false" /> And I want to get the value with something like: int val = sharedPrefs.getInt(key, defaultValue). At the moment I have to use getString and parse the result.

    Read the article

  • Connecting form to database errors

    - by Russell Ehrnsberger
    Hello I am trying to connect a page to a MySQL database for newsletter signup. I have the database with 3 fields, id, name, email. The database is named newsletter and the table is named newsletter. Everything seems to be fine but I am getting this error Notice: Undefined index: Name in C:\wamp\www\insert.php on line 12 Notice: Undefined index: Name in C:\wamp\www\insert.php on line 13 Here is my form code. <form action="insert.php" method="post"> <input type="text" value="Name" name="Name" id="Name" class="txtfield" onblur="javascript:if(this.value==''){this.value=this.defaultValue;}" onfocus="javascript:if(this.value==this.defaultValue){this.value='';}" /> <input type="text" value="Enter Email Address" name="Email" id="Email" class="txtfield" onblur="javascript:if(this.value==''){this.value=this.defaultValue;}" onfocus="javascript:if(this.value==this.defaultValue){this.value='';}" /> <input type="submit" value="" class="button" /> </form> Here is my insert.php file. <?php $host="localhost"; // Host name $username="root"; // Mysql username $password=""; // Mysql password $db_name="newsletter"; // Database name $tbl_name="newsletter"; // Table name // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // Get values from form $name=$_POST['Name']; $email=$_POST['Email']; // Insert data into mysql $sql="INSERT INTO $tbl_name(name, email)VALUES('$name', '$email')"; $result=mysql_query($sql); // if successfully insert data into database, displays message "Successful". if($result){ echo "Successful"; echo "<BR>"; echo "<a href='index.html'>Back to main page</a>"; } else { echo "ERROR"; } ?> <?php // close connection mysql_close(); ?>

    Read the article

  • How much slower is a try/catch block? [closed]

    - by Euclid
    Possible Duplicate: What is the real overhead of try/catch in C#? how much slower is a try catch block than a conditional? eg try { v = someArray[10]; } catch { v = defaultValue; } or if (null != someArray) { v = someArray[10]; } else { v = defaultValue; } is there much in it or isn't there a definative performance differance?

    Read the article

1 2 3 4 5 6 7 8  | Next Page >