Search Results

Search found 1014 results on 41 pages for 'trim'.

Page 9/41 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • PHP email form multiple select

    - by Justin Goodman
    I'm trying to set up a simple PHP contact form for a website and I need some help modifying the PHP to list multiple items from a select menu and would appreciate the help. I'm a graphic designer, not a developer, so a lot of this is way over my head. This is the problem area here: <label for="Events[]">Which Event(s) Will You Be Attending?</label> <div class="input-bg"> <select name="Events[]" size="6" multiple="MULTIPLE" class="required" id="Events[]"> <option value="Wednesday">Portfolio Show June 16</option> <option value="Thursday">Portfolio Show June 17</option> <option value="Saturday">Graduation Ceremony</option> <option value="Saturday Eve">Graduation Party</option> <option value="Not Sure">Not Sure</option> <option value="Not Coming">Not Coming</option> </select> </div> And here's the PHP: <?php // CHANGE THE VARIABLES BELOW $EmailFrom = "[email protected]"; $EmailTo = "[email protected]"; $Subject = "Graduation RSVP"; $Name = Trim(stripslashes($_POST['Name'])); $Email = Trim(stripslashes($_POST['Email'])); $Guests = Trim(stripslashes($_POST['Guests'])); $Events = Trim(stripslashes($_POST['Events'])); // prepare email body text $Body = ""; $Body .= "Name: "; $Body .= $Name; $Body .= "\n"; $Body .= "Email: "; $Body .= $Email; $Body .= "\n"; $Body .= "Guests: "; $Body .= $Guests; $Body .= "\n"; $Body .= "Events: "; $Body .= $Events; $Body .= "\n"; // send email $success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>"); // redirect to success page // CHANGE THE URL BELOW TO YOUR "THANK YOU" PAGE if ($success){ print "<meta http-equiv=\"refresh\" content=\"0;URL=http://justgooddesign.net/graduation\">"; } else{ print "<meta http-equiv=\"refresh\" content=\"0;URL=http://justgooddesign.net/graduation/error.html\">"; } ?> Any help really is appreciated!

    Read the article

  • How to properly document programming languages?

    - by roydukkey
    Where can I find information on how to properly document a programming language? What I mean is that there seems to be a standard way to document code. php.net and api.jquery.com seem to document there code the a similar way. For example, the trim() description on php.net. string trim ( string $str [, string $charlist ] ) And likewise on jquery.com .animate( properties, [ duration ], [ easing ], [ callback ] ) Does anyone even know what this syntax is called?

    Read the article

  • Negate the null-coalescing operator

    - by jhunter
    I have a bunch of strings I need to use .Trim() on, but they can be null. It would be much more concise if I could do something like: string endString = startString !?? startString.Trim(); Basically return the part on the right if the part on the left is NOT null, otherwise just return the null value. I just ended up using the ternary operator, but is there anyway to use the null-coalescing operator for this purpose?

    Read the article

  • MySQL VARCHAR strange column behavior

    - by Mat
    I have the following SQL statement which returns a single record as expected: select * from geodatasource_cities C, geodatasource_countries D where C.CC_FIPS = D.CC_FIPS and D.CC_ISO='AU' and UCASE(TRIM(C.FULL_NAME_ND)) LIKE '%JAN JUE%'; However, If I use the following SQL statement, no records are returned. I have only changed the LIKE clause to an equal to clause: select * from geodatasource_cities C, geodatasource_countries D where C.CC_FIPS = D.CC_FIPS and D.CC_ISO='AU' and UCASE(TRIM(C.FULL_NAME_ND)) = 'JAN JUE'; Can anybody please help me understand why this may be happening?

    Read the article

  • Minimalist array creation in c#

    - by sipwiz
    I've always wanted to be able to use the line below but the C# compiler won't let me. To me it seems obvious and unambiguos as to what I want. myString.Trim({'[', ']'}); I can acheive my goal using: myString.Trim(new char[]{'[', ']'}); So I don't die wondering is there any other way to do it that is closer to the first approach?

    Read the article

  • JavaScript IF with AND/OR.. not working

    - by nobosh
    Can someone who is a master at JS tell me what's wrong with this? if ( $.trim($("#add-box-text").val()).length < 2 && $.trim($("#add-box-text").val()) != "Click here to add an item" ) { // If it's LT than 1 Character, don't submit $("#add-box-text").effect('highlight', {color: '#BDC1C7'}, 500); // Refocus $("#add-box-text").focus(); }

    Read the article

  • can we use jquery for client side validation of a custom validation control?

    - by Mac
    There are two textboxes one for email and other one for phone i have used one custom validation control so that user have to fill any one of textboxes for client side i used javascript function ValidatePhoneEmail(source, args) { var tboxEmail = document.getElementById('<%= tboxEmail.ClientID %>'); var tboxPhone = document.getElementById('<%= tboxPhone.ClientID %>'); if (tboxEmail.value.trim() != '' || tboxPhone.value.trim() != '') { args.IsValid = true; } else { args.IsValid = false; } } how to achieve same result using jquery

    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

  • CodePlex Daily Summary for Saturday, May 15, 2010

    CodePlex Daily Summary for Saturday, May 15, 2010New ProjectsBizTalk EDI Guidance: BizTalk EDI Guidance is intended to simplify the delivery of EDI solutions by leveraging the ESB Toolkit. This project is currently Alpha and sh...Continues Integration Sample: I'm providing a series of blog post to show a complete CI process using CruiseControl.Net and msbuild. The source code for this series is hosted here.DioM2D: My Dragons in our Midst RPG. Runs on my custom Starlight Engine.Ethical Hacking ASP.NET: Security tools and guidelines for white-hat hacking and protecting ASP.NET web applications.Farseer Engine with XNATouch: Farseer is great engine for game physics. This implementation uses XNATouch framework.Feature Builder Guidance Extensions: Feature Builder Guidance Extensions are Feature Extensions which extend the guidance for the Feature Building experience. Each FBGX will be suppli...Microsoft Office Document Security: MODS is a plugin for office 2007 thats includes Hash Encryption, Hex Convertion and more. Plugins: MODS For Word still working on (MODS for Excel ...Minimize Engine (XNA): The Minimize Engine is a basic 3D Games Engine created using XNA, with its primary focus around Grid Based games.MSForge TownCrier: This project is meant to build a notification and calling system for MSForge.net User Groups.NatureProtector: Silverlight 4 project.OutSync: OutSync is a free Windows desktop application that syncs photos of your Facebook friends with matching contacts in Microsoft Outlook. It allows you...Quick Save Images, Clipboard save to file, Quick save, bmp, png, jpeg, Image: ClipSa is a very small tool for very quick picture saving. You put some picture into the clipboard (PrintScrn/Alt-PrintScrn/Ctrl-C), ClipSa saves ...ResHelper Manager: Resource strings management tool that creates localization files for any type of localization target (asp.net, wpf and so on...)SecureCookieHttpModule: Secure your session cookie (and other session-based) cookies for replay attacks using this easy to use ASP.NET HttpModule.simpleChMS: A Church Management System (ChMS) designed for churches or ministries like youth groups that want to facilitate better care or theie membership. Fo...sMAPtool: -SPDomainObject: mapping strong type objects to sp listsSQL Trim: This project aims at developing a universal trim function for Microsoft SQL Server. It trims: 1) pre spaces 2) post spaces 3) double spaces 3) subs...TurretGunner: mt-experienceNew ReleasesBeanProxy: BeanProxy 3.0: BeanProxy is a C# (.NET 3.5) library housing classes that facilitates unit testing. Any non-static, public interface/class or abstract class can be...Blueset Studio Opensource Projects: 蓝色之风记事本 0.2 Alpha: 一个超级Bug版本……CSharp Intellisense: V2.1: - Bug fix (Pascal Casing)DioM2D: DioM2D0.01: http://www.dragonsinourmidst.com/forums/showthread.php?p=690058#post690058Ethical Hacking ASP.NET: Version 1.0.0.1: This is the initial release of the project. Read more about the available tests and features on the Documentation tab. You need the full .NET Frame...Event Scavenger: Collector service update - version 3.2.4: Added check if the database connection string is set up in the config file.Feature Builder Guidance Extensions: FBGX-Binaries: This release consists of a zip file containing all the VSIXs resulting from building each of the FBGX packages found here as source. This will mak...Floe IRC Client: Floe IRC Client 2010-05 R2: - Detaching windows (right click on the tabs to detach them) - Highlight lines with your nick or other patterns - Fixed several bugs - Tabs can now...Free language translator and file converter: Free Language Translator 1.96: Fixed some minor bugs and improved the UI a bit. If you can not install the msi file you might be missing some prerequisites. You can try running t...Geocache Downloader: release 1.0: This is the first release.kp.net: Alpha release is avalable: The goal of this alpha release is to try the code in some production scenarios and find out what features should be tuned.Live-Exchange Calendar Sync: Live-Exchange Calendar Sync: Live-Exchange Calendar Sync Beta May 14, 2010 release of Live-Exchange Calendar Sync 1.0 BETA. (Version 45334) Getting StartedInfo about installat...MAPILab Explorer for SharePoint: MAPILab Explorer for SharePoint ver 2.1.1: 1) Small bug fixed that appears on first start (when earliers versions wasn't installed). How to install:Download ZIP file and extract it on Sha...Microsoft Office Document Security: MODS 4 WORD (SOURCE INCLUDED): Includes Source CodeMoonyDesk (windows desktop widgets): MoonyDesk Alpha: MoonyDesk Alpha (some memory improvements)OnTopReplica: Release 2.9.3: Some bugfixes and improvements. Czech translation added (thanks René Mihula).OutSync: OutSync v1.0.100.0: OutSync v1.0.100.0 is the final release by Mel before the move to CodePlex. I have tested it on Windows 7 32bit and 64bit with Office 2007 and it ...Quick Save Images, Clipboard save to file, Quick save, bmp, png, jpeg, Image: Clipsa v 0.1: Download and extract to any place 2 files - clipSa.exe and clipSa.exe.config Run clipSa.exe. That's all.ResHelper Manager: ResHelperManager: List of changes applied to this version of ResHelper is included in main download zip package. Example sourcesIn Source Code tab are sources of De...Rx Contrib: V1.3: - Bug Fix - BufferWithTimeOrCount with flexible time period setting when ever the time period elapsed...SharePoint DVK Integration: SharePoint 2007 DVK integration v1.0.3: Fixes Fixed default field bindings. I rebound too many fields on every page load. Fixed extension replacing on creating target url (threw it out)...ShoutcastStast for DotNetNuke: DNN_ShoutcastStats alpha 05.00.495: First Alpha release of ShoutcastStats Module for DotNetNuke This first alpha version of the ShoutcastStats Module for DotNetNuke is still in devel...SilverPart 2.1: SilverPart 2.1: SilverPart 2.1 This interim release fixes some major bugs related to Firefox and anonymous access. - Fix for Issue ID 4005 - SilverPart does not w...sMAPtool: sMAPedit v0.7c (Base Release with Maps): Fixed: force a gargabe collection update to prevent pictureBox's memory leak Added: essential map pack with all basic maps in jpg format Added:...SQL Trim: Trim: Initial releaseSSIS Multiple Hash: Multiple Hash V1.2.1: This is version 1.2.1 of the Multiple Hash SSIS Component. It supports SQL 2005 and SQL 2008, although you have to download the correct install pa...StreamInsight Yahoo Finance input adapter example: StockTicker_v1_0_RTM: Updated for StreamInsight RTM.Update Controls .NET: 2.1.0.0: Automatic dependency management for WPF and Silverlight data binding. This release combines both the WPF and Silverlight assemblies into one insta...VCC: Latest build, v2.1.30514.0: Automatic drop of latest buildMost Popular ProjectsRawrWBFS ManagerAJAX Control ToolkitMicrosoft SQL Server Product Samples: DatabaseSilverlight ToolkitWindows Presentation Foundation (WPF)patterns & practices – Enterprise LibraryMicrosoft SQL Server Community & SamplesPHPExcelASP.NETMost Active Projectspatterns & practices – Enterprise LibraryMirror Testing SystemRawrPHPExcelBlogEngine.NETMicrosoft Biology FoundationCustomer Portal Accelerator for Microsoft Dynamics CRMWindows Azure Command-line Tools for PHP DevelopersShake - C# MakeStyleCop

    Read the article

  • $_POST data returns empty when headers are > POST_MAX_SIZE

    - by Jared
    Hi Hopefully someone here might have an answer to my question. I have a basic form that contains simple fields, like name, number, email address etc and 1 file upload field. I am trying to add some validation into my script that detects if the file is too large and then rejects the user back to the form to select/upload a smaller file. My problem is, if a user selects a file that is bigger than my validation file size rule and larger than php.ini POST_MAX_SIZE/UPLOAD_MAX_FILESIZE and pushes submit, then PHP seems to try process the form only to fail on the POST_MAX_SIZE settings and then clears the entire $_POST array and returns nothing back to the form. Is there a way around this? Surely if someone uploads something than the max size configured in the php.ini then you can still get the rest of the $_POST data??? Here is my code. <?php function validEmail($email) { $isValid = true; $atIndex = strrpos($email, "@"); if (is_bool($atIndex) && !$atIndex) { $isValid = false; } else { $domain = substr($email, $atIndex+1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); $domainLen = strlen($domain); if ($localLen < 1 || $localLen > 64) { // local part length exceeded $isValid = false; } else if ($domainLen < 1 || $domainLen > 255) { // domain part length exceeded $isValid = false; } else if ($local[0] == '.' || $local[$localLen-1] == '.') { // local part starts or ends with '.' $isValid = false; } else if (preg_match('/\\.\\./', $local)) { // local part has two consecutive dots $isValid = false; } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { // character not valid in domain part $isValid = false; } else if (preg_match('/\\.\\./', $domain)) { // domain part has two consecutive dots $isValid = false; } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) { // character not valid in local part unless // local part is quoted if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; } } } return $isValid; } //setup post variables @$name = htmlspecialchars(trim($_REQUEST['name'])); @$emailCheck = htmlspecialchars(trim($_REQUEST['email'])); @$organisation = htmlspecialchars(trim($_REQUEST['organisation'])); @$title = htmlspecialchars(trim($_REQUEST['title'])); @$phone = htmlspecialchars(trim($_REQUEST['phone'])); @$location = htmlspecialchars(trim($_REQUEST['location'])); @$description = htmlspecialchars(trim($_REQUEST['description'])); @$fileError = 0; @$phoneError = ""; //setup file upload handler $target_path = 'uploads/'; $filename = basename( @$_FILES['uploadedfile']['name']); $max_size = 8000000; // maximum file size (8mb in bytes) NB: php.ini max filesize upload is 10MB on test environment. $allowed_filetypes = Array(".pdf", ".doc", ".zip", ".txt", ".xls", ".docx", ".csv", ".rtf"); //put extensions in here that should be uploaded only. $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename. if(!is_writable($target_path)) die('You cannot upload to the specified directory, please CHMOD it to 777.'); //Check if we can upload to the specified upload folder. //display form function function displayForm($name, $emailCheck, $organisation, $phone, $title, $location, $description, $phoneError, $allowed_filetypes, $ext, $filename, $fileError) { //make $emailCheck global so function can get value from global scope. global $emailCheck; global $max_size; echo '<form action="geodetic_form.php" method="post" name="contact" id="contact" enctype="multipart/form-data">'."\n". '<fieldset>'."\n".'<div>'."\n"; //name echo '<label for="name"><span class="mandatory">*</span>Your name:</label>'."\n". '<input type="text" name="name" id="name" class="inputText required" value="'. $name .'" />'."\n"; //check if name field is filled out if (isset($_REQUEST['submit']) && empty($name)) { echo '<label for="name" class="error">Please enter your name.</label>'."\n"; } echo '</div>'."\n". '<div>'."\n"; //Email echo '<label for="email"><span class="mandatory">*</span>Your email:</label>'."\n". '<input type="text" name="email" id="email" class="inputText required email" value="'. $emailCheck .'" />'."\n"; // check if email field is filled out and proper format if (isset($_REQUEST['submit']) && validEmail($emailCheck) == false) { echo '<label for="email" class="error">Invalid email address entered.</label>'."\n"; } echo '</div>'."\n". '<div>'."\n"; //organisation echo '<label for="phone">Organisation:</label>'."\n". '<input type="text" name="organisation" id="organisation" class="inputText" value="'. $organisation .'" />'."\n"; echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n"; //title echo '<label for="phone">Title:</label>'."\n". '<input type="text" name="title" id="title" class="inputText" value="'. $title .'" />'."\n"; echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n"; //phone echo '<label for="phone"><span class="mandatory">*</span>Phone <br /><span class="small">(include area code)</span>:</label>'."\n". '<input type="text" name="phone" id="phone" class="inputText required" value="'. $phone .'" />'."\n"; // check if phone field is filled out that it has numbers and not characters if (isset($_REQUEST['submit']) && $phoneError == "true" && empty($phone)) echo '<label for="email" class="error">Please enter a valid phone number.</label>'."\n"; echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n"; //Location echo '<label class="location" for="location"><span class="mandatory">*</span>Location:</label>'."\n". '<textarea name="location" id="location" class="required">'. $location .'</textarea>'."\n"; //check if message field is filled out if (isset($_REQUEST['submit']) && empty($_REQUEST['location'])) echo '<label for="location" class="error">This field is required.</label>'."\n"; echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n"; //description echo '<label class="description" for="description">Description:</label>'."\n". '<textarea name="description" id="queryComments">'. $description .'</textarea>'."\n"; echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n"; //file upload echo '<label class="uploadedfile" for="uploadedfile">File:</label>'."\n". '<input type="file" name="uploadedfile" id="uploadedfile" value="'. $filename .'" />'."\n"; // Check if the filetype is allowed, if not DIE and inform the user. switch ($fileError) { case "1": echo '<label for="uploadedfile" class="error">The file you attempted to upload is not allowed.</label>'; break; case "2": echo '<label for="uploadedfile" class="error">The file you attempted to upload is too large.</label>'; break; } echo '</div>'."\n". '</fieldset>'; //end of form echo '<div class="submit"><input type="submit" name="submit" value="Submit" id="submit" /></div>'. '<div class="clear"><p><br /></p></div>'; } //end function //setup error validations if (isset($_REQUEST['submit']) && !empty($_REQUEST['phone']) && !is_numeric($_REQUEST['phone'])) $phoneError = "true"; if (isset($_REQUEST['submit']) && $_FILES['uploadedfile']['error'] != 4 && !in_array($ext, $allowed_filetypes)) $fileError = 1; if (isset($_REQUEST['submit']) && $_FILES["uploadedfile"]["size"] > $max_size) $fileError = 2; echo "this condition " . $fileError; $POST_MAX_SIZE = ini_get('post_max_size'); $mul = substr($POST_MAX_SIZE, -1); $mul = ($mul == 'M' ? 1048576 : ($mul == 'K' ? 1024 : ($mul == 'G' ? 1073741824 : 1))); if ($_SERVER['CONTENT_LENGTH'] > $mul*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) echo "too big!!"; echo $POST_MAX_SIZE; if(empty($name) || empty($phone) || empty($location) || validEmail($emailCheck) == false || $phoneError == "true" || $fileError != 0) { displayForm($name, $emailCheck, $organisation, $phone, $title, $location, $description, $phoneError, $allowed_filetypes, $ext, $filename, $fileError); echo $fileError; echo "max size is: " .$max_size; echo "and file size is: " . $_FILES["uploadedfile"]["size"]; exit; } else { //copy file from temp to upload directory $path_of_uploaded_file = $target_path . $filename; $tmp_path = $_FILES["uploadedfile"]["tmp_name"]; echo $tmp_path; echo "and file size is: " . filesize($_FILES["uploadedfile"]["tmp_name"]); exit; if(is_uploaded_file($tmp_path)) { if(!copy($tmp_path,$path_of_uploaded_file)) { echo 'error while copying the uploaded file'; } } //test debug stuff echo "sending email..."; exit; } ?> PHP is returning this error in the log: [29-Apr-2010 10:32:47] PHP Warning: POST Content-Length of 57885895 bytes exceeds the limit of 10485760 bytes in Unknown on line 0 Excuse all the debug stuff :) FTR, I am running PHP 5.1.2 on IIS. TIA Jared

    Read the article

  • jquery tabs with form help

    - by sico87
    Hello, I am implementing jQuery tabs on mysite, one of the tabs holds a form and this is my problem, the form is loaded in via ajax as it is used multiple time throughout the site. My issue is that when the form is submitted the page leaves the tabbed area, whereas I need to stay within the tabbed system. Below is the code I am using TABS HTML <div id="tabs"> <ul> <li><a href="#tabs-1">Active Categories</a></li> <li><a href="#tabs-2">De-activated Categories</a></li> <li><a href="<?=base_url();?>admin/addCategory">Add A New Category</a></li> </ul> FORM MARKUP <div id="contact_form"> <?php // open the form echo form_open(base_url().'admin/addCategory'); // categoryTitle echo form_label('Category Name', 'categoryTitle'); echo form_error('categoryTitle'); $data = array( 'name' => 'categoryTitle', 'id' => 'categoryTitle', 'value' => $categoryTitle, ); echo form_input($data); // categoryAbstract $data = array( 'name' => 'categoryAbstract', 'id' => 'categoryAbstract wysiwyg', 'value' => $categoryAbstract, ); echo form_label('Category Abstract', 'categoryAbstract'); echo form_error('categoryAbstract'); echo form_textarea($data); // categorySlug $data = array( 'name' => 'categorySlug', 'id' => 'categorySlug', 'value' => $categorySlug, ); echo form_label('Category Slug', 'categorySlug'); echo form_error('categorySlug'); echo form_input($data); // categoryIsSpecial /*$data = array( 'name' => 'categoryIsSpecial', 'id' => 'categoryIsSpecial', 'value' => '1', 'checked' => $checkedSpecial, ); echo form_label('Is Category Special?', 'categoryIsSpecial'); echo form_error('categoryIsSpecial'); echo form_checkbox($data);*/ // categoryOnline $data = array( 'name' => 'categoryOnline', 'id' => 'categoryOnline', 'value' => '1', 'checked' => $checkedOnline, ); echo form_label('Online?', 'categoryOnline'); echo form_checkbox($data); echo form_error('categoryOnline'); //hidden field check if we are adding or editing echo form_hidden('edit', $edit); echo form_hidden('categoryId', $categoryId); // categorySubmit $data = array('class' => 'submit', 'id' => 'submit', 'value'=>'Submit', 'name' => 'categorySubmit'); echo form_submit($data); echo form_close(); ?> </div> FORM PROCESS function saveCategory() { $data = array(); // we need to set the what element the form errors get displayed in $this->form_validation->set_error_delimiters('<div class="formError">', '</div>'); // we need to estabilsh some rules so the form can be submitted without error, // or if there is error then the form needs show errors. $config = array( array( 'field' => 'categoryTitle', 'label' => 'Category title', 'rules' => 'required|trim|max_length[25]|xss_clean' ), array( 'field' => 'categoryAbstract', 'label' => 'Category abstract', 'rules' => 'required|trim|max_length[150]|xss_clean' ), array( 'field' => 'categorySlug', 'label' => 'Category slug', 'rules' => 'required|trim|alpha|max_length[25]|xss_clean' ), /*array( 'field' => 'categoryIsSpecial', 'label' => 'Special category', 'rules' => 'trim|xss_clean' ),*/ array( 'field' => 'categoryOnline', 'label' => 'Category online', 'rules' => 'trim|xss_clean' ) ); $this->form_validation->set_rules($config); // with the validation rules set we can no run the validation rules over the form // if any the validation returns false then the error messages will be returned to the view // in the delimiters that we set further up the page. if($this->form_validation->run() == FALSE) { // we should reload the form $this->load->view('admin/add_category'); } }

    Read the article

  • How to use a list of values in Excel as filter in a query

    - by Luca Zavarella
    It often happens that a customer provides us with a list of items for which to extract certain information. Imagine, for example, that our clients wish to have the header information of the sales orders only for certain orders. Most likely he will give us a list of items in a column in Excel, or, less probably, a simple text file with the identification code:     As long as the given values ??are at best a dozen, it costs us nothing to copy and paste those values ??in our SSMS and place them in a WHERE clause, using the IN operator, making sure to include the quotes in the case of alphanumeric elements (the database sample is AdventureWorks2008R2): SELECT * FROM Sales.SalesOrderHeader AS SOH WHERE SOH.SalesOrderNumber IN ( 'SO43667' ,'SO43709' ,'SO43726' ,'SO43746' ,'SO43782' ,'SO43796') Clearly, the need to add commas and quotes becomes an hassle when dealing with hundreds of items (which of course has happened to us!). It’d be comfortable to do a simple copy and paste, leaving the items as they are pasted, and make sure the query works fine. We can have this commodity via a User Defined Function, that returns items in a table. Simply we’ll provide the function with an input string parameter containing the pasted items. I give you directly the T-SQL code, where comments are there to clarify what was written: CREATE FUNCTION [dbo].[SplitCRLFList] (@List VARCHAR(MAX)) RETURNS @ParsedList TABLE ( --< Set the item length as your needs Item VARCHAR(255) ) AS BEGIN DECLARE --< Set the item length as your needs @Item VARCHAR(255) ,@Pos BIGINT --< Trim TABs due to indentations SET @List = REPLACE(@List, CHAR(9), '') --< Trim leading and trailing spaces, then add a CR\LF at the end of the list SET @List = LTRIM(RTRIM(@List)) + CHAR(13) + CHAR(10) --< Set the position at the first CR/LF in the list SET @Pos = CHARINDEX(CHAR(13) + CHAR(10), @List, 1) --< If exist other chars other than CR/LFs in the list then... IF REPLACE(@List, CHAR(13) + CHAR(10), '') <> '' BEGIN --< Loop while CR/LFs are over (not found = CHARINDEX returns 0) WHILE @Pos > 0 BEGIN --< Get the heading list chars from the first char to the first CR/LF and trim spaces SET @Item = LTRIM(RTRIM(LEFT(@List, @Pos - 1))) --< If the so calulated item is not empty... IF @Item <> '' BEGIN --< ...insert it in the @ParsedList temporary table INSERT INTO @ParsedList (Item) VALUES (@Item) --(CAST(@Item AS int)) --< Use the appropriate conversion if needed END --< Remove the first item from the list... SET @List = RIGHT(@List, LEN(@List) - @Pos - 1) --< ...and set the position to the next CR/LF SET @Pos = CHARINDEX(CHAR(13) + CHAR(10), @List, 1) --< Repeat this block while the upon loop condition is verified END END RETURN END At this point, having created the UDF, our query is transformed trivially in: SELECT * FROM Sales.SalesOrderHeader AS SOH WHERE SOH.SalesOrderNumber IN ( SELECT Item FROM SplitCRLFList('SO43667 SO43709 SO43726 SO43746 SO43782 SO43796') AS SCL) Convenient, isn’t it? You can find the script DBA_SplitCRLFList.sql here. Bye!!

    Read the article

  • sending sms to mobile from pc using java [closed]

    - by sjohnfernandas
    hi i need to send sms from pc to mobile phone can u people guide me to achieve? i used the following code to send sms to a mobile from pc but i did not get any output and also not getting any error so guide me and point out the mistakes what i have done. package mobilesms; import java.io.; import java.util.; import javax.comm.*; import java.io.IOException; import java.util.Properties; import java.io.InputStream; import java.io.OutputStream; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.DataOutputStream; import java.io.FileOutputStream; public class ReadSimple implements Runnable, SerialPortEventListener { static CommPortIdentifier portId; static Enumeration portList; OutputStream outputstream; InputStream inputStream; SerialPort serialPort; Thread readThread; public static void main(String[] args) { portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (portId.getName().equals("COM1")) { System.out.println("Found port:COM1 "); ReadSimple reader = new ReadSimple(); } } } } public ReadSimple() { try { serialPort = (SerialPort) portId.open("ReadSimpleApp",500); } catch (PortInUseException e) { System.out.println(e); } try { inputStream = serialPort.getInputStream(); OutputStream out=serialPort.getOutputStream(); String line=""; line="AT"+"r\n"; out.write(line.trim().getBytes()); line=""; line="AT+CMGS=7639808583"+"\r\n"; out.write(line.trim().getBytes()); System.out.print(line); line="helloworld"; //line=”ATD 996544325;”+”\r\n”; out.write(line.trim().getBytes()); } catch (IOException e) { serialPort.close(); System.out.println(e); } // catch(InterruptedException E){E.printStackTrace();} try { serialPort.addEventListener(this); } catch (TooManyListenersException e) {System.out.println(e);} serialPort.notifyondataavailable(true); try { serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) {System.out.println(e);} readThread = new Thread(this); readThread.start(); } public void run() { try { Thread.sleep(200); } catch (InterruptedException e) {System.out.println(e);} } public void serialEvent(SerialPortEvent event) { switch(event.getEventType()) { case SerialPortEvent.BI: case SerialPortEvent.OE: case SerialPortEvent.FE: case SerialPortEvent.PE: case SerialPortEvent.CD: case SerialPortEvent.CTS: case SerialPortEvent.DSR: case SerialPortEvent.RI: case SerialPortEvent.OUTPUT_BUFFER_EMPTY: break; case SerialPortEvent.DATA_AVAILABLE: byte[] readBuffer = new byte[10]; try { while (inputStream.available() 0) { int numBytes = inputStream.read(readBuffer); } System.out.println(new String(readBuffer)); } catch (IOException e) {System.out.println(e);} break; } } }

    Read the article

  • Why my register form don't accept spry validation in dw? [migrated]

    - by shaghayeh
    Why my register form don't accept spry validation in dw? Here is my code: <?php if(isset($_POST['go_register'])) { $last_login=jdate('Y/n/j ,H:i:s'); $firstname=trim($_POST['firstname']); $lastname=trim($_POST['lastname']); $email=trim($_POST['username']); $password=sha1($_POST['password']); $register_date=$_POST['register_date']; if(!empty($firstname)&& !empty($lastname)&& !empty($email)&& !empty($password)&& !empty($register_date)){ $reg_query="insert into users(firstname,lastname,email,password,register_date,last_login)values('$firstname','$lastname','$email','$password','$register_date','$last_login')"; $reg_result=mysqli_query($connection,$reg_query); if($reg_result){ echo "ok"; } }//end of not empty }//end of isset ?> <div class="sectionclass"> <script src="../SpryAssets/SpryValidationTextField.js" type="text/javascript"></script> <link href="../SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css"> <h2>??? ??? ???</h2> <form method="post" action="<?php echo $_SERVER['PHP_SELF']."?catid=2"; ?>"> <div> <span style="color:#F00">*</span> <label>??? </label> <span id="sprytextfield1"> <input type="text" name="firstname" /> <span class="textfieldRequiredMsg">A value is required.</span></span></div> <div> <span style="color:#F00">*</span> <label>??? ????????</label><input type="text" name="lastname" /> </div> <div> <span style="color:#F00">*</span> <label>??? ??????(?????)</label><input dir="ltr" type="text" name="username" /> </div> <div> <span style="color:#F00">*</span> <label>??? ????</label><input type="password" name="password" /> </div> <input type="hidden" name="register_date" value="<?php echo jdate('Y/n/j'); ?>"> <div> <input type="submit" name="go_register" value="??? ???"/> </div> </form> </div> <script type="text/javascript"> var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1"); </script>

    Read the article

  • Powershell: Select-Object with additional calculated difference value

    - by David.Chu.ca
    Let me explain my question. I have a daily report about one PC's free space as in text file (sp.txt) like: DateTime FreeSpace(MB) ----- ------------- 03/01/2010 100.43 DateTime FreeSpace(MB) ----- ------------- 03/02/2010 98.31 .... Then I need to use this file as input to generate a report with difference of free space between dates: DateTime FreeSpace(MB) Change ----- ------------- ------ 03/01/2010 100.43 03/02/2010 98.31 2.12 .... Here are some codes I have to get above result without the additional "Change" calculation: Get-Content "C:\report\sp.txt" ` | where {$_.trim().length -gt 0 -and -not ($_ -like "Date*") -and -not ($_ -like "---*")} ` | Select-Object @{Name='DateTime'; expression={[DateTime]::Parse($_.SubString(0, 10).Trim())}}, ` @{Name='FreeSpace(MB)'; expression={$_.SubString(12, 12).Trim()}}, ` | Sort-Object DateTime ` | Select-Object DateTime, 'FreeSpace(MB)' |ft -AutoSize # how to add additional column Change to this Select-Object? My understanding is that Select-Object will return a collection of objects. Here I create this collection from an input text file(parse each line into parts: datetime and freespace(MB)). In order to calculate the difference between dates, I guess that I need to add additional calculated value to the result of the last Select-Object, or pipe the result to another Select-Object with the calculation as additional property or column. In order to do it, I need to get the previous row's FreeSpace value. Not sure if it is possible and how?

    Read the article

  • How to Convert Non-English Characters to English Using JavaScript

    - by Adam Right
    I have a c# function which converts all non-english characters to proper characters for a given text. like as follows public static string convertString(string phrase) { int maxLength = 100; string str = phrase.ToLower(); int i = str.IndexOfAny( new char[] { 's','ç','ö','g','ü','i'}); //if any non-english charr exists,replace it with proper char if (i > -1) { StringBuilder outPut = new StringBuilder(str); outPut.Replace('ö', 'o'); outPut.Replace('ç', 'c'); outPut.Replace('s', 's'); outPut.Replace('i', 'i'); outPut.Replace('g', 'g'); outPut.Replace('ü', 'u'); str = outPut.ToString(); } // if there are other invalid chars, convert them into blank spaces str = Regex.Replace(str, @"[^a-z0-9\s-]", ""); // convert multiple spaces and hyphens into one space str = Regex.Replace(str, @"[\s-]+", " ").Trim(); // cut and trim string str = str.Substring(0, str.Length <= maxLength ? str.Length : maxLength).Trim(); // add hyphens str = Regex.Replace(str, @"\s", "-"); return str; } but i should use same function on client side with javascript. is it possible to convert above function to js ? waiting all kinds of suggestion. thanks in advance..

    Read the article

  • C#, create virtual directory on remote system

    - by sankar
    The following code create only virtual directory on local system , but i need to create on remote sytem ..help me.. Thanks, Sankar DirectoryEntry iisServer; string VirDirSchemaName = "IIsWebVirtualDir"; public DirectoryEntry Connect() { try { if (txtPath.Text.ToLower().Trim() == "localhost") iisServer = new DirectoryEntry("IIS://" + txtPath.Text.Trim() + "/W3SVC/1/Root"); else iisServer = new DirectoryEntry("IIS://" + txtPath.Text + "/Schema/AppIsolated", "XYZ", "xyz"); iisServer.Dispose(); } catch (Exception e) { throw new Exception("Could not connect to: " + txtPath.Text.Trim(), e); } return iisServer; } public void CreateVirtualDirectory(DirectoryEntry iisServer) { DirectoryEntry folderRoot = new DirectoryEntry("IIS://" + txtPath.Text + "/W3SVC/1/Root", "XYZ", "xyz"); folderRoot.RefreshCache(); folderRoot.CommitChanges(); try { DirectoryEntry newVirDir = folderRoot.Children.Add(txtName.Text, VirDirSchemaName); newVirDir.CommitChanges(); newVirDir.Properties["AccessRead"].Add(true); newVirDir.Properties["Path"].Add(@"\\abc\abc"); newVirDir.Invoke("AppCreate", true); newVirDir.CommitChanges(); folderRoot.CommitChanges(); newVirDir.Close(); folderRoot.CommitChanges(); } catch (Exception e) { throw new Exception("Error! Virtual Directory Not Created", e); } } protected void btnCreate_Click(object sender, EventArgs e) { try { CreateVirtualDirectory(Connect()); } catch (Exception ex) { Response.Write(ex.Message); } } protected void Page_Load(object sender, EventArgs e) { }

    Read the article

  • Data from 6 ArrayLists into a single JTable - Java Swing

    - by Splunk
    I have created a JTable which is populated by various arraylists which get their data from a text list using a "~" to split. The issue I am having is that the table is displaying all data from the list on a single row. For example: Column1 Column2 Column2 Column2 Column3 Column4 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 When I want it to display Column1 Column2 Column2 Column2 Column3 Column4 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 You get the idea. From previous advice, I think the issue may be looping, but I am not sure. Any advice would be great. The code is below: private void table(){ String[] colName = { "Course", "Examiner", "Moderator", "Semester Available ", "Associated Programs", "Associated Majors"}; DefaultTableModel model = new DefaultTableModel(colName,0); for(Object item : courseList){ Object[] row = new Object[6]; // String[] row = new String[6]; row[0] = fileManage.getCourseList(); row[1] = fileManage.getNameList(); row[2] = fileManage.getModeratorList(); row[3] = fileManage.getSemesterList(); row[4] = fileManage.getProgramList(); row[5] = fileManage.getMajorList(); model.addRow(row); textArea = new JTable(model); } This is the class that has the arraylists: import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Scanner; public class FileIOManagement { private ArrayList<String> nameList = new ArrayList<String>(); private ArrayList<String> courseList = new ArrayList<String>(); private ArrayList<String> semesterList = new ArrayList<String>(); private ArrayList<String> moderatorList = new ArrayList<String>(); private ArrayList<String> programList = new ArrayList<String>(); private ArrayList<String> majorList = new ArrayList<String>(); public ArrayList<String> getNameList(){ return this.nameList; } public ArrayList<String> getCourseList(){ return this.courseList; } public ArrayList<String> getSemesterList(){ return this.semesterList; } public ArrayList<String> getModeratorList(){ return this.moderatorList; } public ArrayList<String> getProgramList(){ return this.programList; } public ArrayList<String> getMajorList(){ return this.majorList; } public void setNameList(ArrayList<String> nameList){ this.nameList = nameList; } public void setCourseList(ArrayList<String> courseList){ this.courseList = courseList; } public void setSemesterList(ArrayList<String> semesterList){ this.semesterList = semesterList; } public void setModeratorList(ArrayList<String> moderatorList){ this.moderatorList = moderatorList; } public void setProgramList(ArrayList<String> programList){ this.programList = programList; } public void setMajorList(ArrayList<String> majorList){ this.majorList = majorList; } public FileIOManagement(){ setNameList(new ArrayList<String>()); setCourseList(new ArrayList<String>()); setSemesterList(new ArrayList<String>()); setModeratorList(new ArrayList<String>()); setProgramList(new ArrayList<String>()); setMajorList(new ArrayList<String>()); readTextFile(); getNameList(); getCourseList(); } private void readTextFile(){ try{ Scanner scan = new Scanner(new File("Course.txt")); while(scan.hasNextLine()){ String line = scan.nextLine(); String[] tokens = line.split("~"); String course = tokens[0].trim(); String examiner = tokens[1].trim(); String moderator = tokens[2].trim(); String semester = tokens[3].trim(); String program = tokens[4].trim(); String major = tokens[5].trim(); courseList.add(course); semesterList.add(semester); nameList.add(examiner); moderatorList.add(moderator); programList.add(program); majorList.add(major); HashSet hs = new HashSet(); hs.addAll(nameList); nameList.clear(); nameList.addAll(hs); Collections.sort(nameList); } scan.close(); } catch (FileNotFoundException e){ e.printStackTrace(); } } } This is the class where I need to have the JTable: import java.awt.*; import javax.swing.*; import java.io.*; import javax.swing.border.EmptyBorder; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.table.DefaultTableModel; public class AllDataGUI extends JFrame{ private JButton saveCloseBtn = new JButton("Save Changes and Close"); private JButton closeButton = new JButton("Exit Without Saving"); private JFrame frame=new JFrame("Viewing All Program Details"); private final FileIOManagement fileManage = new FileIOManagement(); private ArrayList<String> nameList = new ArrayList(); private ArrayList<String> courseList = new ArrayList(); private ArrayList<String> semesterList = new ArrayList(); private ArrayList<String> moderatorList = new ArrayList(); private ArrayList<String> majorList = new ArrayList(); private ArrayList<String> programList = new ArrayList(); private JTable textArea; public ArrayList<String> getNameList(){ return this.nameList; } public ArrayList<String> getCourseList(){ return this.courseList; } public ArrayList<String> getSemesterList(){ return this.semesterList; } public ArrayList<String> getModeratorList(){ return this.moderatorList; } public ArrayList<String> getProgramList(){ return this.programList; } public ArrayList<String> getMajorList(){ return this.majorList; } public void setNameList(ArrayList<String> nameList){ this.nameList = nameList; } public void setCourseList(ArrayList<String> courseList){ this.courseList = courseList; } public void setSemesterList(ArrayList<String> semesterList){ this.semesterList = semesterList; } public void setModeratorList(ArrayList<String> moderatorList){ this.moderatorList = moderatorList; } public void setProgramList(ArrayList<String> programList){ this.programList = programList; } public void setMajorList(ArrayList<String> majorList){ this.majorList = majorList; } public AllDataGUI(){ getData(); table(); panels(); } public Object getValueAt(int rowIndex, int columnIndex) { String[] token = nameList.get(rowIndex).split(","); return token[columnIndex]; } private void table(){ String[] colName = { "Course", "Examiner", "Moderator", "Semester Available ", "Associated Programs", "Associated Majors"}; DefaultTableModel model = new DefaultTableModel(colName,0); for(Object item : courseList){ Object[] row = new Object[6]; // String[] row = new String[6]; row[0] = fileManage.getCourseList(); row[1] = fileManage.getNameList(); row[2] = fileManage.getModeratorList(); row[3] = fileManage.getSemesterList(); row[4] = fileManage.getProgramList(); row[5] = fileManage.getMajorList(); model.addRow(row); textArea = new JTable(model); // String END_OF_LINE = ","; // // String[] colName = { "Course", "Examiner", "Moderator", "Semester Available ", "Associated Programs", "Associated Majors"}; //// textArea.getTableHeader().setBackground(Color.WHITE); //// textArea.getTableHeader().setForeground(Color.BLUE); // // Font Tablefont = new Font("Details", Font.BOLD, 12); // // textArea.getTableHeader().setFont(Tablefont); // Object[][] object = new Object[100][100]; // int i = 0; // if (fileManage.size() != 0) { // for (fileManage book : fileManage) { // object[i][0] = fileManage.getCourseList(); // object[i][1] = fileManage.getNameList(); // object[i][2] = fileManage.getModeratorList(); // object[i][3] = fileManage.getSemesterList(); // object[i][4] = fileManage.getProgramList(); // object[i][5] = fileManage.getMajorList(); // // textArea = new JTable(object, colName); // } // } } } public void getData(){ nameList = fileManage.getNameList(); courseList = fileManage.getCourseList(); semesterList = fileManage.getSemesterList(); moderatorList = fileManage.getModeratorList(); majorList = fileManage.getMajorList(); programList = fileManage.getProgramList(); // textArea.(write()); } private JButton getCloseButton(){ return closeButton; } private void panels(){ JPanel panel = new JPanel(new GridLayout(1,1)); panel.setBorder(new EmptyBorder(5, 5, 5, 5)); JPanel rightPanel = new JPanel(new GridLayout(15,0,10,10)); rightPanel.setBorder(new EmptyBorder(15, 5, 5, 10)); JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); panel.add(scrollBarForTextArea); frame.add(panel); frame.getContentPane().add(rightPanel,BorderLayout.EAST); rightPanel.add(saveCloseBtn); rightPanel.add(closeButton); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.dispose(); } }); saveCloseBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //saveBtn(); frame.dispose(); } }); frame.setSize(1000, 700); frame.setVisible(true); frame.setLocationRelativeTo(null); } // private void saveBtn(){ // File file = null; // FileWriter out=null; // try { // file = new File("Course.txt"); // out = new FileWriter(file); // out.write(textArea.getText()); // out.close(); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // JOptionPane.showMessageDialog(this, "File Successfully Updated"); // // } }

    Read the article

  • The following code to check if a file exists on a server does not work

    - by xplorer2k
    Hi Everyone, I found the following code to check if a file exists on a server, but is not working for me. It tells me that "test1.tx" does not exist even though the file exists and its size is 498 bytes. If I try with Ftp.ListDirectory it tells me that the file does not exist. If I try with Ftp.GetFileSize it does not provide any results and the debugger's immediate gives me the following message: A first chance exception of type 'System.Net.WebException' occurred in System.dll. Using "request.UseBinary = true" does not make any difference. I have posted this same question at this link: http://social.msdn.microsoft.com/Forums/en-US/ncl/thread/89e05cf3-189f-48b7-ba28-f93b1a9d44ae Could someone help me how to fix it? private void button1_Click(object sender, EventArgs e) { string ftpServerIP = txtIPaddress.Text.Trim(); string ftpUserID = txtUsername.Text.Trim(); string ftpPassword = txtPassword.Text.Trim(); try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + ftpServerIP + "//tmp/test1.txt"); request.Method = WebRequestMethods.Ftp.ListDirectory; //request.Method = WebRequestMethods.Ftp.GetFileSize; request.Credentials = new NetworkCredential(ftpUserID, ftpPassword); //request.UseBinary = true; using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { // Okay. textBox1.AppendText(Environment.NewLine); textBox1.AppendText("File exist"); } } catch (WebException ex) { if (ex.Response != null) { FtpWebResponse response = (FtpWebResponse)ex.Response; if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { // Directory not found. textBox1.AppendText(Environment.NewLine); textBox1.AppendText("File does not exist"); } } } } Thanks very much, xplorer2k

    Read the article

  • Turning PHP page calling Zend functions procedurally into Zend Framework MVC-help!

    - by Joel
    Hi guys, I posted much of this question, but if didn't include all the Zend stuff because I thought it'd be overkill, but now I'm thinking it's not easy to figure out an OO way of doing this without that code... So with that said, please forgive the verbose code. I'm learning how to use MVC and OO in general, and I have a website that is all in PHP but most of the pages are basic static pages. I have already converted them all to views in Zend Framework, and have the Controller and layout set. All is good there. The one remaining page I have is the main reason I did this...it in fact uses Zend library (for gData connection and pulling info from a Google Calendar and displaying it on the page. I don't know enough about this to know where to begin to refactor the code to fit in the Zend Framework MVC model. Any help would be greatly appreciated!! .phtml view page: <div id="dhtmltooltip" align="left"></div> <script src="../js/tooltip.js" type="text/javascript"> </script> <div id="container"> <div id="conten"> <a name="C4"></a> <?php function get_desc_second_part(&$value) { list(,$val_b) = explode('==',$value); $value = trim($val_b); } function filterEventDetails($contentText) { $data = array(); foreach($contentText as $row) { if(strstr($row, 'When: ')) { ##cleaning "when" string to get date in the format "May 28, 2009"## $data['duration'] = str_replace('When: ','',$row); list($when, ) = explode(' to ',$data['duration']); $data['when'] = substr($when,4); if(strlen($data['when'])>13) $data['when'] = trim(str_replace(strrchr($data['when'], ' '),'',$data['when'])); $data['duration'] = substr($data['duration'], 0, strlen($data['duration'])-4); //trimming time zone identifier (UTC etc.) } if(strstr($row, 'Where: ')) { $data['where'] = str_replace('Where: ','',$row); //pr($row); //$where = strstr($row, 'Where: '); //pr($where); } if(strstr($row, 'Event Description: ')) { $event_desc = str_replace('Event Description: ','',$row); //$event_desc = strstr($row, 'Event Description: '); ## Filtering event description and extracting venue, ticket urls etc from it. //$event_desc = str_replace('Event Description: ','',$contentText[3]); $event_desc_array = explode('|',$event_desc); array_walk($event_desc_array,'get_desc_second_part'); //pr($event_desc_array); $data['venue_url'] = $event_desc_array[0]; $data['details'] = $event_desc_array[1]; $data['tickets_url'] = $event_desc_array[2]; $data['tickets_button'] = $event_desc_array[3]; $data['facebook_url'] = $event_desc_array[4]; $data['facebook_icon'] = $event_desc_array[5]; } } return $data; } // load library require_once 'Zend/Loader.php'; Zend_Loader::loadClass('Zend_Gdata'); Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); Zend_Loader::loadClass('Zend_Gdata_Calendar'); Zend_Loader::loadClass('Zend_Http_Client'); // create authenticated HTTP client for Calendar service $gcal = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; $user = "[email protected]"; $pass = "xxxxxxxx"; $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $gcal); $gcal = new Zend_Gdata_Calendar($client); $query = $gcal->newEventQuery(); $query->setUser('[email protected]'); $secondary=true; $query->setVisibility('private'); $query->setProjection('basic'); $query->setOrderby('starttime'); $query->setSortOrder('ascending'); //$query->setFutureevents('true'); $startDate=date('Y-m-d h:i:s'); $endDate="2015-12-31"; $query->setStartMin($startDate); $query->setStartMax($endDate); $query->setMaxResults(30); try { $feed = $gcal->getCalendarEventFeed($query); } catch (Zend_Gdata_App_Exception $e) { echo "Error: " . $e->getResponse(); } ?> <h1><?php echo $feed->title; ?></h1> <?php echo $feed->totalResults; ?> event(s) found. <table width="90%" border="3" align="center"> <tr> <td width="20%" align="center" valign="middle"><b>;DATE</b></td> <td width="25%" align="center" valign="middle"><b>VENUE</b></td> <td width="20%" align="center" valign="middle"><b>CITY</b></td> <td width="20%" align="center" valign="middle"><b>DETAILS</b></td> <td width="15%" align="center" valign="middle"><b>LINKS</b></td> </tr> <?php if((int)$feed->totalResults>0) { //checking if at least one event is there in this date range foreach ($feed as $event) { //iterating through all events //pr($event);die; $contentText = stripslashes($event->content->text); //striping any escape character $contentText = preg_replace('/\<br \/\>[\n\t\s]{1,}\<br \/\>/','<br />',stripslashes($event->content->text)); //replacing multiple breaks with a single break //die(); $contentText = explode('<br />',$contentText); //splitting data by break tag $eventData = filterEventDetails($contentText); $when = $eventData['when']; $where = $eventData['where']; $duration = $eventData['duration']; $venue_url = $eventData['venue_url']; $details = $eventData['details']; $tickets_url = $eventData['tickets_url']; $tickets_button = $eventData['tickets_button']; $facebook_url = $eventData['facebook_url']; $facebook_icon = $eventData['facebook_icon']; $title = stripslashes($event->title); echo '<tr>'; echo '<td width="20%" align="center" valign="middle" nowrap="nowrap">'; echo $when; echo '</td>'; echo '<td width="20%" align="center" valign="middle">'; if($venue_url!='') { echo '<a href="'.$venue_url.'" target="_blank">'.$title.'</a>'; } else { echo $title; } echo '</td>'; echo '<td width="20%" align="center" valign="middle">'; echo $where; echo '</td>'; echo '<td width="20%" align="center" valign="middle">'; $details = str_replace("\n","<br>",htmlentities($details)); $duration = str_replace("\n","<br>",$duration); $detailed_description = "<b>When</b>: <br>".$duration."<br><br>"; $detailed_description .= "<b>Description</b>: <br>".$details; echo '<a href="javascript:void(0);" onmouseover="ddrivetip(\''.$detailed_description.'\')" onmouseout="hideddrivetip()" onclick="return false">View Details</a>'; echo '</td>'; echo '<td width="20%" valign="middle">'; if(trim($tickets_url) !='' && trim($tickets_button)!='') { echo '<a href="'.$tickets_url.'" target="_blank"><img src="'.$tickets_button.'" border="0" ></a>'; } if(trim($facebook_url) !='' && trim($facebook_icon)!='') { echo '<a href="'.$facebook_url.'" target="_blank"><img src="'.$facebook_icon.'" border="0" ></a>'; } else { echo '......'; } echo '</td>'; echo '</tr>'; } } else { //else show 'no event found' message echo '<tr>'; echo '<td width="100%" align="center" valign="middle" colspan="5">'; echo "No event found"; echo '</td>'; } ?> </table> <h3><a href="#pastevents">Scroll down for a list of past shows.</a></h3> <br /> <a name="pastevents"></a> <ul class="pastShows"> <?php $startDate='2005-01-01'; $endDate=date('Y-m-d'); /*$gcal = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; $user = "[email protected]"; $pass = "silverroof10"; $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $gcal); $gcal = new Zend_Gdata_Calendar($client); $query = $gcal->newEventQuery(); $query->setUser('[email protected]'); $query->setVisibility('private'); $query->setProjection('basic');*/ $query->setOrderby('starttime'); $query->setSortOrder('descending'); $query->setFutureevents('false'); $query->setStartMin($startDate); $query->setStartMax($endDate); $query->setMaxResults(1000); try { $feed = $gcal->getCalendarEventFeed($query); } catch (Zend_Gdata_App_Exception $e) { echo "Error: " . $e->getResponse(); } if((int)$feed->totalResults>0) { //checking if at least one event is there in this date range foreach ($feed as $event) { //iterating through all events $contentText = stripslashes($event->content->text); //striping any escape character $contentText = preg_replace('/\<br \/\>[\n\t\s]{1,}\<br \/\>/','<br />',stripslashes($event->content->text)); //replacing multiple breaks with a single break $contentText = explode('<br />',$contentText); //splitting data by break tag $eventData = filterEventDetails($contentText); $when = $eventData['when']; $where = $eventData['where']; $duration = $eventData['duration']; $title = stripslashes($event->title); echo '<li class="pastShows">' . $when . " - " . $title . ", " . $where . '</li>'; } } ?> </div> </div>

    Read the article

  • Why do I get "mysql_query(): supplied argument is not a valid"

    - by Brian Ojeda
    Why do I get a "mysql_query(): supplied argument is not a valid" for the first... $r = mysql_query($q, $connection); In the following code... $bId = trim($_POST['bId']); $title = trim($_POST['title']); $story = trim($_POST['story']); $q = "SELECT * "; $q .= "FROM " . DB_NAME . ".`blog` "; $q .= "WHERE `blog`.`id` = {$bId}"; $r = mysql_query($q, $connection); //confirm_query($r); if (mysql_num_rows($r) == 1) { $q = "UPDATE " . DB_NAME . ".`blog` SET `title` = '{$title}', `story` = '{$story}' WHERE `id` = {$bId}"; $r = mysql_query($q, $connection); if (mysql_affected_rows() == 1) { //Successful $data['success'] = true; $date['errors'] = false; $date['message'] = "You are the Greatest!"; } else { //Fail $data['success'] = false; $data['error'] = true; $date['message'] = "You can't do it fool!"; } } I also get an "mysql_num_rows(): supplied argument is not a valid MySQL result resource" error too. Side notes: I am using 1&1 Hosting (worst hosting ever), custom .htaccess file with one line text to enable PHP 5.2 (only why with 1&1 Hosting).

    Read the article

  • Multithreading A Function in VB.Net

    - by Ben
    I am trying to multi thread my application so as it is visible while it is executing the process, this is what I have so far: Private Sub SendPOST(ByVal URL As String) Try Dim DataBytes As Byte() = Encoding.ASCII.GetBytes("") Dim Request As HttpWebRequest = TryCast(WebRequest.Create(URL.Trim & "/webdav/"), HttpWebRequest) Request.Method = "POST" Request.ContentType = "application/x-www-form-urlencoded" Request.ContentLength = DataBytes.Length Request.Timeout = 1000 Request.ReadWriteTimeout = 1000 Dim PostData As Stream = Request.GetRequestStream() PostData.Write(DataBytes, 0, DataBytes.Length) Dim Response As WebResponse = Request.GetResponse() Dim ResponseStream As Stream = Response.GetResponseStream() Dim StreamReader As New IO.StreamReader(ResponseStream) Dim Text As String = StreamReader.ReadToEnd() PostData.Close() Catch ex As Exception If ex.ToString.Contains("401") Then TextBox2.Text = TextBox2.Text & URL & "/webdav/" & vbNewLine End If End Try End Sub Public Sub G0() Dim siteSplit() As String = TextBox1.Text.Split(vbNewLine) For i = 0 To siteSplit.Count - 1 Try If siteSplit(i).Contains("http://") Then SendPOST(siteSplit(i).Trim) Else SendPOST("http://" & siteSplit(i).Trim) End If Catch ex As Exception End Try Next End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim t As Thread t = New Thread(AddressOf Me.G0) t.Start() End Sub However, the 'G0' sub code is not being executed at all, and I need to multi thread the 'SendPOST' as that is what slows the application.

    Read the article

  • Radio Button selection Changes Toast on Android

    - by Bub
    I was writing a simple test application. There are two radio buttons within the app. There id's are "radio_red" and "radio_blue". I wanted to create an onClickListener event that read the text associated to the button and then returned a basic "Right" or "Wrong" toast. Here is a sample of the code: private OnClickListener radio_listener = new OnClickListener() { public void onClick(View v){ RadioButton rb = (RadioButton) v; String ans = rb.getText().toString(); String an1 = ""; if (ans.trim() == "Yes") { ans = "That's Right."; } else if (ans.trim() == "No") { ans = "thats wrong."; } else { ans = "none."; } Toast.makeText(v.getContext(), ans , Toast.LENGTH_SHORT).show(); } So far no joy. Here is my code snippet. I've checked my "main.xml" and the text associated to the buttons are referneced correctly. I added trim to make sure of that. However, all that is ever returned in the toast is "none." What am I missing? Thanks in advance for any help.

    Read the article

  • My IF statement is changing variables in PHP

    - by user1902509
    I am fairly new to the whole programming thing, so forgive me if this is a stupid question. It seems odd that I haven't run into it before. I am trying to make an order form for a cake. You fill out the form, submit it, and it will then display the order in a new window, where you then hit "submit," and upload it to the Database. I have a series of If Statements to check for errors in the form before submitting it. Here is a simplified version of the code. Writing means any writing you want on the cake, Name is your name, and cake is what type of cake you want (the default is "None"). try { $name = trim($params->name); $cake = trim($params->cake); $writing = trim($params->writing); if (strlen($name) < 3){ throw new Exception("Please enter Your name."); } if ($cake = "None") { throw new Exception("Please select a Cake" } if ($cake = "Caramel Apple Pie" or $cake = "Pumpkin Pie" or $cake = "Eggnog Pie" and strlen($writing) > 1) { throw new Exception("We are sorry, but you can't write on any of our specialty pies."); } } catch(Exception $x) { $error = $x->getmessage(); } So what is happening is that when I go and hit submit the first time, the correct cake type comes up, but when you submit it the second time, the error comes up saying that I have "None" selected. All the other values are there and remain the same. I think the problem is that the first "IF" statement (Where it says "If($cake = "None")) is automatically changing $cake to "None" because I have tried commenting just that statement out, and it will then change the cake to be "Caramel Apple Pie," which is in the top of the next IF statement. Anyone know why it is doing this? And how to fix it?

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >