Search Results

Search found 3112 results on 125 pages for 'daylight saving'.

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

  • Android: Resolution issue while saving image into gallery

    - by Luca D'Amico
    I've managed to programmatically take a photo from the camera, then display it on an imageview, and then after pressing a button, saving it on the Gallery. It works, but the problem is that the saved photo are low resolution.. WHY?! I took the photo with this code: Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST); Then I save the photo on a var using : protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_PIC_REQUEST) { thumbnail = (Bitmap) data.getExtras().get("data"); } } and then after displaying it on an imageview, I save it on the gallery with this function: public void SavePicToGallery(Bitmap picToSave, File savePath){ String JPEG_FILE_PREFIX= "PIC"; String JPEG_FILE_SUFFIX= ".JPG"; String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_"; File filePath = null; try { filePath = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, savePath); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } FileOutputStream out = null; try { out = new FileOutputStream(filePath); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } picToSave.compress(CompressFormat.JPEG, 100, out); try { out.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Add the pic to Android Gallery String mCurrentPhotoPath = filePath.getAbsolutePath(); MediaScannerConnection.scanFile(this, new String[] { mCurrentPhotoPath }, null, new MediaScannerConnection.OnScanCompletedListener() { public void onScanCompleted(String path, Uri uri) { } }); } I really can't figure out why it lose so much quality while saved.. Any help please ? Thanks..

    Read the article

  • core data saving in textboxes in table view controller

    - by user1489709
    I have created a five column (text boxes) cell (row) in table view controller with an option of add button. When a user clicks on add button, a new row (cell) with five column (text boxe) is added in a table view controller with null values. I want that when user fills the text boxes the data should get saved in database or if he changes any data in previous text boxes also it get saved. this is my save btn coding.. -(void)textFieldDidEndEditing:(UITextField *)textField { row1=textField.tag; NSLog(@"Row is %d",row1); path = [NSIndexPath indexPathForRow:row1 inSection:0]; Input_Details *inputDetailsObject1=[self.fetchedResultsController objectAtIndexPath:path]; /* Update the Input Values from the values in the text fields. */ EditingTableViewCell *cell; cell = (EditingTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row1 inSection:0]]; inputDetailsObject1.mh_Up= cell.cell_MH_up.text; inputDetailsObject1.mh_down=cell.cell_MH_dn.text; inputDetailsObject1.sewer_No=[NSNumber numberWithInt:[cell.cell_Sewer_No.text intValue]]; inputDetailsObject1.mhup_gl=[NSNumber numberWithFloat:[cell.cell_gl_MHUP.text floatValue]]; inputDetailsObject1.mhdn_gl=[NSNumber numberWithFloat:[cell.cell_gl_MHDN.text floatValue]]; inputDetailsObject1.pop_Ln=[NSNumber numberWithInt:[cell.cell_Line_pop.text intValue]]; inputDetailsObject1.sew_len=[NSNumber numberWithFloat:[cell.cell_Sewer_len.text floatValue]]; [self saveContext]; NSLog(@"Saving the MH_up value %@ is saved in save at index path %d",inputDetailsObject1.mh_Up,row1); [self.tableView reloadData]; }

    Read the article

  • download file, without saving in server

    - by lolalola
    Hi, Or possible for users to download the file without saving it on the server? I am getting data from the database, and I want to save them .doc (MS Word) file. if(isset($_POST['save'])) { $file = "new_file2.doc"; $stringData = "Text text text text...."; //This data put in new Word file $fh = fopen($file, 'w'); fwrite($fh, $stringData); fclose($fh); header('Content-Description: File Transfer'); header('Content-type: application/msword'); header('Content-Disposition: attachment; filename="'.$file.'"'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); unlink($file); exit; } How should the code look like without this: " $fh = fopen($file, 'w'); fwrite($fh, $stringData); fclose($fh);" and this "unlink($file);" I hope to understand what I need enter code here

    Read the article

  • Saving a single entity instead of the entire context - revisited

    - by nite
    I’m looking for a way to have fine grained control over what is saved using Entity Framework, rather than the whole ObjectContext.SaveChanges(). My scenario is pretty straight forward, and I’m quite amazed not catered for in EF – pretty basic in NHibernate and all other data access paradigms I’ve seen. I’m generating a bunch of data (in a WPF UI) and allowing the user to fine tune what is proposed and choose what is actually committed to the database. For the proposed entities I’m: getting a bunch of reference entities (eg languages) via my objectcontext, creating the proposed entities and assigning these reference entities to them (as navigation properties), so by virtue of their relationship to the reference entities they’re implicitly added to the objectconext Trying to create & save individual entites based on the proposed entities. I figure this should be really simple & trivial but everything I’ve tried I’ve hit a brick wall, either I set up another objectcontext & add just the entity I need (it then tries to add the whole graph and fails as it’s on another objectcontext). I’ve tried MergeOptions = NoTracking on my reference entities to try to get the Attach/AddObject not to navigate through these to create a graph, no avail. I've removed the navigation properties from the reference entities. I've tried AcceptAllChanges, that works but pretty useless in practice as I do still want to track & save other entities. In a simple test, I can create 2 of my proposed entities, AddObject the one I want to save and then Detach the one I dont then call SaveChanges, this works but again not great in practice. Following are a few links to some of the nifty ideas which in the end don’t help in the end but illustrate the complexity of EF for something so simple. I’m really looking for a SaveSingle/SaveAtomic method, and think it’s a pretty reasonable & basic ask for any DAL, letalone a cutting edge ORM. http://stackoverflow.com/questions/1301460/saving-a-single-entity-instead-of-the-entire-context www.codeproject.com/KB/architecture/attachobjectgraph.aspx?fid=1534536&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=3071122&fr=1 bernhardelbl.spaces.live.com/blog/cns!DB54AE2C5D84DB78!238.entry

    Read the article

  • Saving ntext data from SQL Server to file directory using asp

    - by April
    A variety of files (pdf, images, etc.) are stored in a ntext field on a MS SQL Server. I am not sure what type is in this field, other than it shows question marks and undefined characters, I am assuming they are binary type. The script is supposed to iterate through the rows and extract and save these files to a temp directory. "filename" and "contenttype" are given, and "data" is whatever is in the ntext field. I have tried several solutions: 1) data.SaveToFile "/temp/"&filename, 2 Error: Object required: '????????????????????' ??? 2) File.WriteAllBytes "/temp/"&filename, data Error: Object required: 'File' I have no idea how to import this, or the Server for MapPath. (Cue: what a noob!) 3) Const adTypeBinary = 1 Const adSaveCreateOverWrite = 2 Dim BinaryStream Set BinaryStream = CreateObject("ADODB.Stream") BinaryStream.Type = adTypeBinary BinaryStream.Open BinaryStream.Write data BinaryStream.SaveToFile "C:\temp\" & filename, adSaveCreateOverWrite Error: Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another. 4) Response.ContentType = contenttype Response.AddHeader "content-disposition","attachment;" & filename Response.BinaryWrite data response.end This works, but the file should be saving to the server instead of popping up save-as dialog. I am not sure if there is a way to save the response to file. Thanks for shedding light on any of these problems!

    Read the article

  • Saving form values to database after a user logs in

    - by redfalcon
    Hi. We have a form with ratings to submit for a certain restaurant. After the user has entered some values and wants to submit them, we check whether the user is logged in or not. If not, we display a login form and let the user put in his account data and redirect him to the restaurant he wanted to submit a rating for. The problem is, that after he successfully logged in himself, the submitted values are not saved to the database (which works fine if the user is already logged in). So I wondered if it is possible, to somehow save the data although the user is not logged in. I thought of maybe saving the filled values in a variable and have then automatically re-entered after we redirected the user. But I guess this wont work because we use before_filter :login_required, :only => [ :create ] So we couldnt even access the filled in values, since we display the login-form before the method has processed the values in the form, right? Any idea how we can make rails to save the values or at least have them automatically re-entered to the form? Thanks!

    Read the article

  • not saving when using setDidReceiveDataSelector

    - by coder4xc
    i want to download a file and show the progress bar i was able to do this. now , i want to show the progress value in a label and use this code to progress init and update label : [queue setDelegate:self]; [queue setRequestDidFinishSelector:@selector(updateLabel)]; [queue setDownloadProgressDelegate:progress]; [queue setShowAccurateProgress:YES]; ASIHTTPRequest *request; request = [ASIHTTPRequest requestWithURL:url]; [request setDelegate:self]; [request setTemporaryFileDownloadPath:[filePath stringByAppendingString:@".download"]]; [request setAllowResumeForFileDownloads:YES]; [request setDidFinishSelector:@selector(updateLabel)]; [request setDidReceiveDataSelector:@selector(updateLabel)]; [request setShouldContinueWhenAppEntersBackground:YES]; [request setShouldAttemptPersistentConnection:NO]; [request setDownloadDestinationPath:filePath]; [queue addOperation:request]; [queue go]; but not save in the destination path ! and when i clear this code :  [request setDidReceiveDataSelector:@selector(updateLabel)]; saving done ! what is problem ? i want to update label text when progress value changed

    Read the article

  • Saving image to server with php

    - by salmon
    Hey i have the following script, basicaly a flash file sends it some data and it creates a image and then opens a save as dialog box for the user so that they can save the image to there system.Here the problem comes in, how would i go about also saving the image to my server? <?php $to = $_POST['to']; $from = $_POST['from']; $fname = $_POST['fname']; $send = $_POST['send']; $data = explode(",", $_POST['img']); $width = $_POST['width']; $height = $_POST['height']; $image=imagecreatetruecolor( $width ,$height ); $background = imagecolorallocate( $image ,0 , 0 , 0 ); //Copy pixels $i = 0; for($x=0; $x<=$width; $x++){ for($y=0; $y<=$height; $y++){ $int = hexdec($data[$i++]); $color = ImageColorAllocate ($image, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int); imagesetpixel ( $image , $x , $y , $color ); } } //Output image and clean #header("Content-Disposition: attachment; filename=test.jpg" ); header("Content-type: image/jpeg"); ImageJPEG( $image ); imagedestroy( $image ); ?> Help would be greatly appreciated!

    Read the article

  • Split user.config into different files for faster saving (at runtime)

    - by HorstWalter
    In my c# Windows Forms application (.net 3.5 / VS 2008) I have 3 settings files resulting in one user.config file. One setting file consists of larger data, but is rarely changed. The frequently changed data are very few. However, since the saving of the settings is always writing the whole (XML) file it is always "slow". SettingsSmall.Default.Save(); // slow, even if SettingsSmall consists of little data Could I configure the settings somehow to result in two files, resulting in: SettingsSmall.Default.Save(); // should be fast SettingsBig.Default.Save(); // could be slow, is seldom saved I have seen that I can use the SecionInformation class for further customizing, however what would be the easiest approach for me? Is this possible by just changing the app.config (config.sections)? --- added information about App.config The reason why I get one file might be the configSections in the App.config. This is how it looks: <configSections <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" <section name="XY.A.Properties.Settings2Class" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" / <section name="XY.A.Properties.Settings3Class" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" / </sectionGroup </configSections I got the sections when I've added the 2nd and 3rd settings file. I have not paid any attention to this, so it was somehow the default of VS 2008. The single user.config has these 3 sections, it is absolutely transparent. Only I do not know how to tell the App.config to create three independent files instead of one. I have "played around" with the app.config above, but e.g. when I remove the config sections my applications terminates with an exception.

    Read the article

  • C# Custom user settings class not saving

    - by Zenox
    I have the following class: [Serializable] [XmlRoot ( ElementName = "TextData", IsNullable = false)] public class TextData { private System.Drawing.Font fontColor; [XmlAttribute ( AttributeName = "Font" )] public System.Drawing.Font Font { get; set; } [XmlAttribute ( AttributeName = "FontColor" )] public System.Drawing.Color FontColor { get; set; } [XmlAttribute ( AttributeName = "Text" )] public string Text { get; set; } public TextData ( ) { } // End of TextData } // End of TextData And Im attempting to save it with the following code: // Create our font dialog FontDialog fontDialog = new FontDialog ( ); fontDialog.ShowColor = true; // Display the dialog and check for an ok if ( DialogResult.OK == fontDialog.ShowDialog ( ) ) { // Save our changes for the font settings if ( null == Properties.Settings.Default.MainHeadlineTextData ) { Properties.Settings.Default.MainHeadlineTextData = new TextData ( ); } Properties.Settings.Default.MainHeadlineTextData.Font = fontDialog.Font; Properties.Settings.Default.MainHeadlineTextData.FontColor = fontDialog.Color; Properties.Settings.Default.Save ( ); } Everytime I load the the application, the Properties.Settings.Default.MainHeadlineTextData is still null. Saving does not seem to take effect. I read on another post that the class must be public and it is. Any ideas why this would not be working properly?

    Read the article

  • Saving Data to Relational Database (Entity Framework)

    - by sheefy
    I'm having a little bit of trouble saving data to a database. Basically, I have a main table that has associations to other tables (Example Below). Tbl_Listing ID UserID - Associated to ID in User Table CategoryID - Associated to ID in Category Table LevelID - Associated to ID in Level Table. Name Address Normally, it's easy for me to add data to the DB (using Entity Framework). However, I'm not sure how to add data to the fields with associations. The numerous ID fields just need to hold an int value that corresponds with the ID in the associated table. For example; when I try to access the column in the following manner I get a "Object reference not set to an instance of an object." error. Listing NewListing = new Listing(); NewListing.Tbl_User.ID = 1; NewListing.Tbl_Category.ID = 2; ... DBEntities.AddToListingSet(NewListing); DBEntities.SaveChanges(); I am using NewListing.Tbl_User.ID instead of NewListing.UserID because the UserID field is not available through intellisense. If I try and create an object for each related field I get a "The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects." error. With this method, I am trying to add the object without the .ID shown above - example NewListing.User = UserObject. I know this should be simple as I just want to reference the ID from the associated table in the main Listing's table. Any help would be greatly appreciated. Thanks in advance, -S

    Read the article

  • problem in saving drag&drop object in database

    - by Mac Taylor
    hey guys i made a script inspired by wordpress widgets'page to drag&drop blocks of my sites but problem is in saving the position after droping this is jquery code , i used to do the above target : <script type="text/javascript" >$(function(){ $('.widget') .each(function(){ $(this).hover(function(){ $(this).find('h4').addClass('collapse'); }, function(){ $(this).find('h4').removeClass('collapse'); }) .find('h4').hover(function(){ $(this).find('.in-widget-title').css('visibility', 'visible'); }, function(){ $(this).find('.in-widget-title').css('visibility', 'hidden'); }) .click(function(){ $(this).siblings('.widget-inside').toggle(); //Save state on change of collapse state of panel updateWidgetData(); }) .end() .find('.in-widget-title').css('visibility', 'hidden'); }); $('.column').sortable({ connectWith: '.column', handle: 'h4', cursor: 'move', placeholder: 'placeholder', forcePlaceholderSize: true, opacity: 0.4, start: function(event, ui){ //Firefox, Safari/Chrome fire click event after drag is complete, fix for that if($.browser.mozilla || $.browser.safari) $(ui.item).find('.widget-inside').toggle(); }, stop: function(event, ui){ ui.item.css({'top':'0','left':'0'}); //Opera fix if(!$.browser.mozilla && !$.browser.safari) updateWidgetData(); } }) .disableSelection(); }); function updateWidgetData(){ var items=[]; $('.column').each(function(){ var columnId=$(this).attr('id'); $('.widget', this).each(function(i){ var collapsed=0; if($(this).find('.widget-inside').css('display')=="none") collapsed=1; //Create Item object for current panel var item={ id: $(this).attr('id'), collapsed: collapsed, order : i, column: columnId }; //Push item object into items array items.push(item); }); }); //Assign items array to sortorder JSON variable var sortorder={ items: items }; //Pass sortorder variable to server using ajax to save state $.post('updatePanels.php', 'data='+$.toJSON(sortorder), function(response){ if(response=="success") $("#console").html('<div class="success">Saved</div>').hide().fadeIn(1000); setTimeout(function(){ $('#console').fadeOut(1000); }, 2000); }); } </script> and a simple php file but problem is its not sending data to target php file is there anything wrong with my code ?

    Read the article

  • Converting Multiple files to zip and saving them in ownCloud

    - by user1055380
    I wanted to convert an array with some css, js and html files into a zip file and save them in ownCloud (it has it's own framework but it's knowledge is not required.) What I am saving is an infinite loop of zip files, as in, a zip inside a zip so I can't even check that the code is working correctly or not. Please help. Here is the link to the code. <?php /* creates a compressed zip file */ $filename = $_GET["filename"]; function create_zip($files = array(),$destination = '',$overwrite = false) { //if the zip file already exists and overwrite is false, return false if(file_exists($destination) && !$overwrite) { return false; } //vars $valid_files = array(); //if files were passed in... if(is_array($files)) { //cycle through each file foreach($files as $file => $local) { //make sure the file exists if(file_exists($file)) { $valid_files[$file] = $local; } } } //if we have good files... if(count($valid_files)) { //create the archive $zip = new ZipArchive(); if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) { return false; } //add the files foreach($valid_files as $file => $local) { $zip->addFile($file, $local); } //debug //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status; //close the zip -- done! $zip->close(); //check to make sure the file exists return file_exists($destination); } else { return false; } } $files_to_zip = array( 'apps/impressionist/css/mappingstyle.css' => '/css/mappingstyle.css', 'apps/impressionist/css/style.css' => '/css/style.css', 'apps/impressionist/js/jquery.js' => '/scripts/jquery.js', 'apps/impressionist/js/impress.js' => '/scripts/impress.js', realpath('apps/impressionist/output/'.$filename.'.html') => $filename.'.html' ); //if true, good; if false, zip creation failed $result = create_zip($files_to_zip, $filename.'.zip'); $save_file = OC_App::getStorage('impressionist'); $save_file ->file_put_contents($filename.'.zip',$files_to_zip); ?>

    Read the article

  • Creating and Saving an Excel File

    - by Kris
    I have the following code that creates a new Excel file in my C# code behind. When I attempt to save the file I would like the user to select the location of the save. In Method #1, I can save the file my using the workbook SaveCopyAs without prompting the user for a location. This saves one file to the C:\Temp directory. Method #2 will save the file in my Users\Documents folder, then prompt the user to select the location and save a second copy. How can I eliminate the first copy from saving in the Users\Documents folder? Excel.Application oXL; Excel._Workbook oWB; Excel._Worksheet oSheet; Excel.Range oRng; try { //Start Excel and get Application object. oXL = new Excel.Application(); oXL.Visible = false; //Get a new workbook. oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value)); oSheet = (Excel._Worksheet)oWB.ActiveSheet; // ***** oSheet.Cells[2, 6] = "Ship To:"; oSheet.get_Range("F2", "F2").Font.Bold = true; oSheet.Cells[2, 7] = sShipToName; oSheet.Cells[3, 7] = sAddress; oSheet.Cells[4, 7] = sCityStateZip; oSheet.Cells[5, 7] = sContactName; oSheet.Cells[6, 7] = sContactPhone; oSheet.Cells[9, 1] = "Shipment No:"; oSheet.get_Range("A9", "A9").Font.Bold = true; oSheet.Cells[9, 2] = sJobNumber; oSheet.Cells[9, 6] = "Courier:"; oSheet.get_Range("F9", "F9").Font.Bold = true; oSheet.Cells[9, 7] = sCarrierName; oSheet.Cells[11, 1] = "Requested Delivery Date:"; oSheet.get_Range("A11", "A11").Font.Bold = true; oSheet.Cells[11, 2] = sRequestDeliveryDate; oSheet.Cells[11, 6] = "Courier Acct No:"; oSheet.get_Range("F11", "F11").Font.Bold = true; oSheet.Cells[11, 7] = sCarrierAcctNum; // ***** Method #1 //oWB.SaveCopyAs(@"C:\Temp\" + sJobNumber +".xls"); Method #2 oXL.SaveWorkspace(sJobNumber + ".xls"); } catch (Exception theException) { String errorMessage; errorMessage = "Error: "; errorMessage = String.Concat(errorMessage, theException.Message); errorMessage = String.Concat(errorMessage, " Line: "); errorMessage = String.Concat(errorMessage, theException.Source); }

    Read the article

  • ASP.NET MVC 2 - Saving child entities on form submit

    - by Justin
    Hey, I'm using ASP.NET MVC 2 and am struggling with saving child entities. I have an existing Invoice entity (which I create on a separate form) and then I have a LogHours view that I'd like to use to save InvoiceLog's, which are child entities of Invoice. Here's the view: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TothSolutions.Data.Invoice>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Log Hours </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server"> <script type="text/javascript"> $(document).ready(function () { $("#InvoiceLogs_0__Description").focus(); }); </script> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Log Hours</h2> <% using (Html.BeginForm("SaveHours", "Invoices")) {%> <%: Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <table> <tr> <th>Date</th> <th>Description</th> <th>Hours</th> </tr> <% int index = 0; foreach (var log in Model.InvoiceLogs) { %> <tr> <td><%: log.LogDate.ToShortDateString() %></td> <td><%: Html.TextBox("InvoiceLogs[" + index + "].Description")%></td> <td><%: Html.TextBox("InvoiceLogs[" + index + "].Hours")%></td> <td>Hours</td> </tr> <% index++; } %> </table> <p> <%: Html.Hidden("InvoiceID") %> <%: Html.Hidden("CreateDate") %> <input type="submit" value="Save" /> </p> </fieldset> <% } %> <div> <%: Html.ActionLink("Back to List", "Index") %> </div> </asp:Content> And here's the controller code: //GET: /Secure/Invoices/LogHours/ public ActionResult LogHours(int id) { var invoice = DataContext.InvoiceData.Get(id); if (invoice == null) { throw new Exception("Invoice not found with id: " + id); } return View(invoice); } //POST: /Secure/Invoices/SaveHours/ [AcceptVerbs(HttpVerbs.Post)] public ActionResult SaveHours([Bind(Exclude = "InvoiceLogs")]Invoice invoice) { TryUpdateModel(invoice.InvoiceLogs, "InvoiceLogs"); invoice.UpdateDate = DateTime.Now; invoice.DeveloperID = DeveloperID; //attaching existing invoice. DataContext.InvoiceData.Attach(invoice); //save changes. DataContext.SaveChanges(); //redirect to invoice list. return RedirectToAction("Index"); } And the data access code: public static void Attach(Invoice invoice) { var i = new Invoice { InvoiceID = invoice.InvoiceID }; db.Invoices.Attach(i); db.Invoices.ApplyCurrentValues(invoice); } In the SaveHours action, it properly sets the values of the InvoiceLog entities after I call TryUpdateModel but when it does SaveChanges it doesn't update the database with the new values. Also, if you manually update the values of the InvoiceLog entries in the database and then go to this page it doesn't populate the textboxes so it's clearly not binding correctly. Thanks, Justin

    Read the article

  • My PNG has transparency, but after saving with PHP GD, transparency is lost [closed]

    - by Harry Stroker
    I found the solution to my problem. See below the original post and completely at the bottom my solution. I made a stupid mistake :) First I crop an image and then save it to a png file. Right after this, I also show the image. However, the saved png does not have transparency and the shown one has. What is going on? $this->resource = imagecreatefrompng($this->url); imagealphablending($this->resource, false); imagesavealpha($this->resource, true); $newResource = imagecreatetruecolor($destWidth, $destHeight); imagealphablending($newResource, false); imagesavealpha($newResource, true); $resample = imagecopyresampled($newResource,$this->resource,0,0,$srcX1,$srcY1,$destWidth,$destHeight,$srcX2-$srcX1, $srcY2-$srcY1); imagedestroy($this->resource); $this->resource = $newResource; // SAVING imagepng($this->resource, $destination, 100); // SHOWING header('Content-type: image/png'); imagepng($this->resource); The reason I also save the image is for caching. If the script is executed on a png, it saves a cached png. Next time the image is requested, the png file will be shown, but it has lost its transparency. Even stranger: When I save that cached png image as (within Firefox), it saves it suddenly as a jpg, even though the extension was png. Downloading the cached png using chrome and opening it in Photoshop gives the error: "file-format module cannot parse the file". I will show you the shown PNG and the generated PNG: http://www.foodmuseum.nl/SaveProblemTransparency.png Once I try to show that saved PNG with the GD library, it gives me an error. EDIT NO NO NO NO THIS IS NOT A DUPLICATE!!!... I ALREADY USED THEIR SOLUTION. The solution in the supposedly duplicate works for showing my image. But I also try to save it with the exact same resource, but then it has no transparency. EDIT 2 - SOLUTION I found out what the problem was. It was a stupid mistake. The script I provided above were cut out of a class and placed as sequential code, while in real this is not what exactly happened. The save image function: function saveImage($destination,$quality = 90) { $this->loadResource(); switch($extension){ default: case 'JPG': case 'jpg': imagejpeg($this->resource, $destination, $quality); break; case 'gif': imagegif($this->resource, $destination); break; case 'png': imagepng($this->resource, $destination); break; case 'gd2': imagegd2($this->resource, $destination); break; } } However... $extension does not exist. I fixed it by adding: $extension = $this->getExtension($destination);

    Read the article

  • Saving child collections with NHibernate

    - by Ben
    Hi, I am in the process or learning NHibernate so bare with me. I have an Order class and a Transaction class. Order has a one to many association with transaction. The transaction table in my database has a not null constraint on the OrderId foreign key. Order class: public class Order { public virtual Guid Id { get; set; } public virtual DateTime CreatedOn { get; set; } public virtual decimal Total { get; set; } public virtual ICollection<Transaction> Transactions { get; set; } public Order() { Transactions = new HashSet<Transaction>(); } } Order Mapping: <class name="Order" table="Orders"> <cache usage="read-write"/> <id name="Id"> <generator class="guid"/> </id> <property name="CreatedOn" type="datetime"/> <property name="Total" type="decimal"/> <set name="Transactions" table="Transactions" lazy="false" inverse="true"> <key column="OrderId"/> <one-to-many class="Transaction"/> </set> Transaction Class: public class Transaction { public virtual Guid Id { get; set; } public virtual DateTime ExecutedOn { get; set; } public virtual bool Success { get; set; } public virtual Order Order { get; set; } } Transaction Mapping: <class name="Transaction" table="Transactions"> <cache usage="read-write"/> <id name="Id" column="Id" type="Guid"> <generator class="guid"/> </id> <property name="ExecutedOn" type="datetime"/> <property name="Success" type="bool"/> <many-to-one name="Order" class="Order" column="OrderId" not-null="true"/> Really I don't want a bidirectional association. There is no need for my transaction objects to reference their order object directly (I just need to access the transactions of an order). However, I had to add this so that Order.Transactions is persisted to the database: Repository: public void Update(Order entity) { using (ISession session = NHibernateHelper.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { session.Update(entity); foreach (var tx in entity.Transactions) { tx.Order = entity; session.SaveOrUpdate(tx); } transaction.Commit(); } } } My problem is that this will then issue an update for every transaction on the order collection (regardless of whether it has changed or not). What I was trying to get around was having to explicitly save the transaction before saving the order and instead just add the transactions to the order and then save the order: public void Can_add_transaction_to_existing_order() { var orderRepo = new OrderRepository(); var order = orderRepo.GetById(new Guid("aa3b5d04-c5c8-4ad9-9b3e-9ce73e488a9f")); Transaction tx = new Transaction(); tx.ExecutedOn = DateTime.Now; tx.Success = true; order.Transactions.Add(tx); orderRepo.Update(order); } Although I have found quite a few articles covering the set up of a one-to-many association, most of these discuss retrieving of data and not persisting back. Many thanks, Ben

    Read the article

  • ASP.net MVC DropLownList db.SaveChanges not saving selection

    - by WMIF
    I have looked through a ton of tutorials and suggestions on how to work with DropDownList in MVC. I was able to get most of it working, but the selected item is not saving into the database. I am using MVC 3 and Razor for the view. My DropDownList is getting created with the correct values and good looking HTML. When I set a breakpoint, I can see the correct selected item ID in the model getting sent to controller. When the view goes back to the index, the DropDownList value is not set. The other values save just fine. Here are the related views. The DropDownList is displaying a list of ColorModel names as text with the ID as the value. public class ItemModel { [Key] public int ItemID { get; set; } public string Name { get; set; } public string Description { get; set; } public virtual ColorModel Color { get; set; } } public class ItemEditViewModel { public int ItemID { get; set; } public string Name { get; set; } public string Description { get; set; } public int ColorID { get; set; } public IEnumerable<SelectListItem> Colors { get; set; } } public class ColorModel { [Key] public int ColorID { get; set; } public string Name { get; set; } public virtual IList<ItemModel> Items { get; set; } } Here are the controller actions. public ActionResult Edit(int id) { ItemModel itemmodel = db.Items.Find(id); ItemEditViewModel itemEditModel; itemEditModel = new ItemEditViewModel(); itemEditModel.ItemID = itemmodel.ItemID; if (itemmodel.Color != null) { itemEditModel.ColorID = itemmodel.Color.ColorID; } itemEditModel.Description = itemmodel.Description; itemEditModel.Name = itemmodel.Name; itemEditModel.Colors = db.Colors .ToList() .Select(x => new SelectListItem { Text = x.Name, Value = x.ColorID.ToString() }); return View(itemEditModel); } [HttpPost] public ActionResult Edit(ItemEditViewModel itemEditModel) { if (ModelState.IsValid) { ItemModel itemmodel; itemmodel = new ItemModel(); itemmodel.ItemID = itemEditModel.ItemID; itemmodel.Color = db.Colors.Find(itemEditModel.ColorID); itemmodel.Description = itemEditModel.Description; itemmodel.Name = itemEditModel.Name; db.Entry(itemmodel).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(itemEditModel); } The view has this for the DropDownList, and the others are just EditorFor(). @Html.DropDownListFor(model => model.ColorID, Model.Colors, "Select a Color") When I set the breakpoint on the db.Color.Find(...) line, I show this in the Locals window for itemmodel.Color: {System.Data.Entity.DynamicProxies.ColorModel_0EB80C07207CA5D88E1A745B3B1293D3142FE2E644A1A5202B90E5D2DAF7C2BB} When I expand that line, I can see the ColorID that I chose from the dropdown box, but it does not save into the database.

    Read the article

  • Is text-only mode a saving or a problem for battery savings?

    - by Robottinosino
    A friend is flying to the US from Europe and asked me a very thought-provoking question, which I am not remotely able to answer with substance so I am asking it here: How to absolutely maximise battery life on an Ubuntu (laptop) install? do not rush to mark this as duplicate, there is an important point here: does -GNOME- help or worsen battery life? Let me provide some context: The only task he needs to perform is: edit text files in Vim. He is unsure whether running GNOME will drain his battery life more or actually save him some battery life given the smarts of GNOME's power management features like "switch this peripheral to -power save- after X minutes..." (GNOME might just be a configuration front-end for settings that are governed by command-line utils for all I know?) He could perfectly well boot the system in text-only mode and use the automatic 6 virtual consoles for his needs, if that's a saving at all over running tmux (I think so because of all the smart buffering/history/etc the latter does by default?) Exactly how would you advise him to run his laptop during his flight? What I told him already: power off WiFi in the BIOS, not from the "GUI" power off Bluetooth switch off the courtesy light and use low monitor brightness play music off of his phone, not mp3blaster do not use his tiny portable mouse (and do not attach any other USB gimmicks like "screen light", etc) stop development services he will not be using, especially apache2, tomcat, dovecot, postgresql, etc. Potentially: - switch off his cron jobs? (he does an rsync + tar + 7za of his "work in progress" every so often) I think the above is standard stuff one could get off StackExchange, and with many duplicates... the core of this question is, I think: __ will running Ubuntu in text-only mode be a saving in terms of battery life or a problem? why? (provide some technical arguments) __ I think it will be a saving but I am also scared about "other things" detecting and enabling advanced chipset power management features only when some services are started.. and fear these "services" may be off in text-only mode?

    Read the article

  • Getting parameter sent via html form and saving in my db

    - by Wesley
    I have error in my code i don't know to solve it please help me: My Servlet: package br.com.cad.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import br.com.cad.dao.Cadastro; import br.com.cad.basica.Contato; public class AddDados extends HttpServlet{ protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); String nome = request.getParameter("nome"); String sobrenome = request.getParameter("sobrenome"); String rg = request.getParameter("rg"); String cpf = request.getParameter("cpf"); String sexo = request.getParameter("sexo"); StringBuilder finalDate = new StringBuilder("DataNascimento1") .append("/"+request.getParameter("DataNascimento??2")) .append("/"+request.getParameter("DataNascimento3")); try { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); finalDate.toString(); } catch(ParseException e) { out.println("Erro de conversão da data"); return; } Contato contato = new Contato(); contato.setNome(nome); contato.setSobrenome(sobrenome); contato.setRg(rg); contato.setCpf(cpf); contato.setSexo(sexo); if ("Masculino".equals(contato.getSexo())) { contato.setSexo("M"); } else { contato.setSexo("F"); } contato.setDataNascimento1(dataNascimento1); //error here ????? contato.setDataNascimento2(dataNascimento2); //error here ????? contato.setDataNascimento3(dataNascimento3); //error here ????? Cadastro dao = new Cadastro(); dao.adiciona(contato); out.println("<html>"); out.println("<body>"); out.println("Contato " + contato.getNome() + " adicionado com sucesso"); out.println("</body>"); out.println("</html>"); } } My object dao package br.com.cad.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Date; import br.com.cad.dao.ConnectDb; import br.com.cad.basica.Contato; public class Cadastro { private Connection connection; public Cadastro() { this.connection = new ConnectDb().getConnection(); } public void adiciona(Contato contato) { String sql = "INSERT INTO dados_cadastro(pf_nome, pf_ultimonome, pf_rg, pf_cpf, pf_sexo,pf_dt_nasc) VALUES(?,?,?,?,?,?,?,?)"; try { PreparedStatement stmt = connection.prepareStatement(sql); stmt.setString(1, contato.getNome()); stmt.setString(2, contato.getSobrenome()); stmt.setString(3, contato.getRg()); stmt.setString(4, contato.getCpf()); stmt.setString(5, contato.getSexo()); stmt.setDate(6, new Date( contato.getDataNascimento1().getTimeInMillis()) ); // i think there are error here i don't know to solve it ????? stmt.execute(); stmt.close(); System.out.println("Cadastro realizado com sucesso!."); } catch(SQLException sqlException) { throw new RuntimeException(sqlException); } } } My class cadastro package br.com.cad.basica; import java.util.Calendar; public class Contato { private Long id; private String nome; private String sobrenome; private String email; private String endereco; private Calendar dataNascimento1; private Calendar dataNascimento2; private Calendar dataNascimento3; private String rg; private String cpf; private String sexo; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } ...getters and setters I need to saving data in my mysql db, but i have some doubt about this code main how to get parameter send form html combobox( 1 for day, 2 for month, 3 for year of birth) i concatened with StringBuilder finalDate ... so i have some problem in my code please help me!!!

    Read the article

  • Saving a Join Model

    - by Thorpe Obazee
    I've been reading the cookbook for a while now and still don't get how I'm supposed to do this: My original problem was this: A related Model isn't being validated From RabidFire's commment: If you want to count the number of Category models that a new Post is associated with (on save), then you need to do this in the beforeSave function as I've mentioned. As you've currently set up your models, you don't need to use the multiple rule anywhere. If you really, really want to validate against a list of Category IDs for some reason, then create a join model, and validate category_id with the multiple rule there. Now, I have these models and are now validating. The problem now is that data isn't being saved in the Join Table: class Post extends AppModel { var $name = 'Post'; var $hasMany = array( 'CategoryPost' => array( 'className' => 'CategoryPost' ) ); var $belongsTo = array( 'Page' => array( 'className' => 'Page' ) ); class Category extends AppModel { var $name = 'Category'; var $hasMany = array( 'CategoryPost' => array( 'className' => 'CategoryPost' ) ); class CategoryPost extends AppModel { var $name = 'CategoryPost'; var $validate = array( 'category_id' => array( 'rule' => array('multiple', array('in' => array(1, 2, 3, 4))), 'required' => FALSE, 'message' => 'Please select one, two or three options' ) ); var $belongsTo = array( 'Post' => array( 'className' => 'Post' ), 'Category' => array( 'className' => 'Category' ) ); This is the new Form: <div id="content-wrap"> <div id="main"> <h2>Add Post</h2> <?php echo $this->Session->flash();?> <div> <?php echo $this->Form->create('Post'); echo $this->Form->input('Post.title'); echo $this->Form->input('CategoryPost.category_id', array('multiple' => 'checkbox')); echo $this->Form->input('Post.body', array('rows' => '3')); echo $this->Form->input('Page.meta_keywords'); echo $this->Form->input('Page.meta_description'); echo $this->Form->end('Save Post'); ?> </div> <!-- main ends --> </div> The data I am producing from the form is as follows: Array ( [Post] => Array ( [title] => 1234 [body] => 1234 ) [CategoryPost] => Array ( [category_id] => Array ( [0] => 1 [1] => 2 ) ) [Page] => Array ( [meta_keywords] => 1234 [meta_description] => 1234 [title] => 1234 [layout] => index ) ) UPDATE: controller action //Controller action function admin_add() { // pr(Debugger::trace()); $this->set('categories', $this->Post->CategoryPost->Category->find('list')); if ( ! empty($this->data)) { $this->data['Page']['title'] = $this->data['Post']['title']; $this->data['Page']['layout'] = 'index'; debug($this->data); if ($this->Post->saveAll($this->data)) { $this->Session->setFlash('Your post has been saved', 'flash_good'); $this->redirect($this->here); } } } UPDATE #2: Should I just do this manually? The problem is that the join tables doesn't have things saved in it. Is there something I'm missing? UPDATE #3 RabidFire gave me a solution. I already did this before and am quite surprised as so why it didn't work. Thus, me asking here. The reason I think there is something wrong. I don't know where: Post beforeSave: function beforeSave() { if (empty($this->id)) { $this->data[$this->name]['uri'] = $this->getUniqueUrl($this->data[$this->name]['title']); } if (isset($this->data['CategoryPost']['category_id']) && is_array($this->data['CategoryPost']['category_id'])) { echo 'test'; $categoryPosts = array(); foreach ($this->data['CategoryPost']['category_id'] as $categoryId) { $categoryPost = array( 'category_id' => $categoryId ); array_push($categoryPosts, $categoryPost); } $this->data['CategoryPost'] = $categoryPosts; } debug($this->data); // Gives RabidFire's correct array for saving. return true; } My Post action: function admin_add() { // pr(Debugger::trace()); $this->set('categories', $this->Post->CategoryPost->Category->find('list')); if ( ! empty($this->data)) { $this->data['Page']['title'] = $this->data['Post']['title']; $this->data['Page']['layout'] = 'index'; debug($this->data); // First debug is giving the correct array as above. if ($this->Post->saveAll($this->data)) { debug($this->data); // STILL gives the above array. which shouldn't be because of the beforeSave in the Post Model // $this->Session->setFlash('Your post has been saved', 'flash_good'); // $this->redirect($this->here); } } }

    Read the article

  • Effects of enabling DVFS in a CPU

    - by Nrew
    I came up with this energy regulating software called Granola while reading at Ghacks.net I downloaded and installed the software but you need to enable the DVFS function in the CPU. I booted up and tried to enable DVFS in the CPU Configuration in my Asus motherboard(Desktop). But in the description it said that enabling the feature might raise some compatibility issues with the power supply. And I'm afraid that I might ruin the CPU if I do this. Any suggestions, any one here who has tried this before? I don't know who the manufacturer of my power supply is. Would you recommend some software that can determine every possible info about the power supply.

    Read the article

  • how did my laptop lose daylight savings time on power loss?

    - by EndangeringSpecies
    it was an old laptop that may or may not have dead CMOS battery (at least it had time reset to 0 when I dusted it off). So, it was plugged into power for awhile without the main battery and the clock was correct. Then there was a power outage. When I subsequently turned it on, surprise-surprise, it had one hour off correct time. So the clock apparently kept running during the outage, but daylight savings time info vanished (from disk? where is it stored?) How come?

    Read the article

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