Search Results

Search found 24848 results on 994 pages for 'true soft'.

Page 25/994 | < Previous Page | 21 22 23 24 25 26 27 28 29 30 31 32  | Next Page >

  • LINQ Query returns false when it should be true.

    - by deliriousDev
    I have the following LINQ query written by a former developer and it isn't working when it should. public bool IsAvailable(Appointment appointment) { var appointments = _appointmentRepository.Get; var shifts = _scheduleRepository.Get; var city = _customerRepository.Find(appointment.CustomerId).City ?? appointment.Customer.City; const int durationHour = 1; DateTime scheduledEndDate = appointment.ScheduledTime.Add(new TimeSpan(durationHour, 0, 0)); var inWorkingHours = shifts .Where(x => //Check if any available working hours x.Employee.City == city && x.ShiftStart <= appointment.ScheduledTime && x.ShiftEnd >= scheduledEndDate && //check if not booked yet !appointments .Where(a => (appointment.Id == 0 || a.Id != appointment.Id) && a.Employee.Id == x.Employee.Id && ( (a.ScheduledTime <= appointment.ScheduledTime && appointment.ScheduledTime <= EntityFunctions.AddHours(a.ScheduledTime, durationHour)) || (a.ScheduledTime <= scheduledEndDate && scheduledEndDate <= EntityFunctions.AddHours(a.ScheduledTime, durationHour)) )) .Select(a => a.Employee.Id) .Contains(x.Employee.Id) ); if (inWorkingHours.Any()) { var assignedEmployee = inWorkingHours.FirstOrDefault().Employee; appointment.EmployeeId = assignedEmployee.Id; appointment.Employee = assignedEmployee; return true; } return false; } The query is suppose to handle the following scenarios Given An Appointment With A ScheduledTime Between A ShiftStart and ShiftEnd time But Does not match any employees in same city - (Return true, Assign as "Unassigned") Given An Appointment With A ScheduledTime Between A ShiftStart and ShiftEnd time AND Employee for that shift is in the same city as the customer (Return True AND Assign to the employee) If the customer is NOT in the same city as an employee we assign the appointment as "Unassigned" as along as the scheduledTime is within an of the employees shift start/end times If the customer is in the same city as an employee we assign the appointment to one of the employees (firstOrdefault) and occupy that timeslot. Appointments CAN NOT overlap (Assigned Ones). Unassigned can't overlap each other. This query use to work (I've been told). But now it doesn't and I have tried refactoring it and various other paths with no luck. I am now on week two and just don't know where the issue in the query is or how to write it. Let me know if I need to post anything further. I have verified appointments, shifts, city all populate with valid data so the issue doesn't appear to be with null or missing data.

    Read the article

  • How to access a list in OCaml

    - by Erik
    I want to write a function that could check every item in a list is true or false. If at least one element is false, it will return true, so that: assert_eq "checkFalse [true; false; true]" (checkFalse [true; true; true]) false; assert_eq "checkFalse [false; false]" (checkFalse [false; true]) true; I am an absolute beginner in OCaml and I don't know how to approach this. I tried using a for loop, something like: let rec checkFalse (bools: bool list) : bool = for i = 0 to bools.length do if bools.length == false then false else... (I don't know how to continue) Then it said "Unbound record field...." I also tried using find like: if (find false bools != Not_found) then true else false But my ways did not work. I came from a Java background. Thank you very much!

    Read the article

  • Creating a file upload template in Doctrine ORM

    - by balupton
    Hey all. I'm using Doctrine 1.2 as my ORM for a Zend Framework Project. I have defined the following Model for a File. File: columns: id: primary: true type: integer(4) unsigned: true code: type: string(255) unique: true notblank: true path: type: string(255) notblank: true size: type: integer(4) type: type: enum values: [file,document,image,video,audio,web,application,archive] default: unknown notnull: true mimetype: type: string(20) notnull: true width: type: integer(2) unsigned: true height: type: integer(2) unsigned: true Now here is the File Model php class (just skim through for now): <?php /** * File * * This class has been auto-generated by the Doctrine ORM Framework * * @package ##PACKAGE## * @subpackage ##SUBPACKAGE## * @author ##NAME## <##EMAIL##> * @version SVN: $Id: Builder.php 6365 2009-09-15 18:22:38Z jwage $ */ class File extends BaseFile { public function setUp ( ) { $this->hasMutator('file', 'setFile'); parent::setUp(); } public function setFile ( $file ) { global $Application; // Configuration $config = array(); $config['bal'] = $Application->getOption('bal'); // Check the file if ( !empty($file['error']) ) { $error = $file['error']; switch ( $file['error'] ) { case UPLOAD_ERR_INI_SIZE : $error = 'ini_size'; break; case UPLOAD_ERR_FORM_SIZE : $error = 'form_size'; break; case UPLOAD_ERR_PARTIAL : $error = 'partial'; break; case UPLOAD_ERR_NO_FILE : $error = 'no_file'; break; case UPLOAD_ERR_NO_TMP_DIR : $error = 'no_tmp_dir'; break; case UPLOAD_ERR_CANT_WRITE : $error = 'cant_write'; break; default : $error = 'unknown'; break; } throw new Doctrine_Exception('error-application-file-' . $error); return false; } if ( empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name']) ) { throw new Doctrine_Exception('error-application-file-invalid'); return false; } // Prepare config $file_upload_path = realpath($config['bal']['files']['upload_path']) . DIRECTORY_SEPARATOR; // Prepare file $filename = $file['name']; $file_old_path = $file['tmp_name']; $file_new_path = $file_upload_path . $filename; $exist_attempt = 0; while ( file_exists($file_new_path) ) { // File already exists // Pump exist attempts ++$exist_attempt; // Add the attempt to the end of the file $file_new_path = $file_upload_path . get_filename($filename,false) . $exist_attempt . get_extension($filename); } // Move file $success = move_uploaded_file($file_old_path, $file_new_path); if ( !$success ) { throw new Doctrine_Exception('Unable to upload the file.'); return false; } // Secure $file_path = realpath($file_new_path); $file_size = filesize($file_path); $file_mimetype = get_mime_type($file_path); $file_type = get_filetype($file_path); // Apply $this->path = $file_path; $this->size = $file_size; $this->mimetype = $file_mimetype; $this->type = $file_type; // Apply: Image if ( $file_type === 'image' ) { $image_dimensions = image_dimensions($file_path); if ( !empty($image_dimensions) ) { // It is not a image we can modify $this->width = 0; $this->height = 0; } else { $this->width = $image_dimensions['width']; $this->height = $image_dimensions['height']; } } // Done return true; } /** * Download the File * @return */ public function download ( ) { global $Application; // File path $file_upload_path = realpath($config['bal']['files']['upload_path']) . DIRECTORY_SEPARATOR; $file_path = $file_upload_path . $this->file_path; // Output result and download become_file_download($file_path, null, null); die(); } public function postDelete ( $Event ) { global $Application; // Prepare $Invoker = $Event->getInvoker(); // Configuration $config = array(); $config['bal'] = $Application->getOption('bal'); // File path $file_upload_path = realpath($config['bal']['files']['upload_path']) . DIRECTORY_SEPARATOR; $file_path = $file_upload_path . $this->file_path; // Delete the file unlink($file_path); // Done return true; } } What I am hoping to accomplish is so that the above custom functionality within my model file can be turned into a validator, template, or something along the lines. So hopefully I can do something like: File: actAs: BalFile: columns: id: primary: true type: integer(4) unsigned: true code: type: string(255) unique: true notblank: true path: type: string(255) notblank: true size: type: integer(4) type: type: enum values: [file,document,image,video,audio,web,application,archive] default: unknown notnull: true mimetype: type: string(20) notnull: true width: type: integer(2) unsigned: true height: type: integer(2) unsigned: true I'm hoping for a validator so that say if I do $File->setFile($_FILE['uploaded_file']); It will provide a validation error, except in all the doctrine documentation it has little on custom validators, especially in the contect of "virtual" fields. So in summary, my question is: How earth can I go about making a template/extension to porting this functionality? I have tried before with templates but always gave up after a day :/ If you could take the time to port the above I would greatly appreciate it.

    Read the article

  • YUI Datatable Not Taking JSON

    - by Pete Herbert Penito
    I am trying to fill a Datatable with a JSON using YUI, I have this JSON: [{"test":"value1", "test2":"value2", "test3":"value3", "topic_id":"123139007E57", "gmt_timestamp":1553994442, "timestamp_diff":-1292784933382, "status":"images\/statusUp.png", "device_id":"568FDE9CC7275FA"}, .. It continues like this with about 20 different devices, and I close it with a ] I just want to print select keys in the datatable so my Column Definitions look like this: var myColumnDefs = [ {key:"test", sortable:true, resizeable:true}, {key:"test2", sortable:true, resizeable:true}, {key:"topic_id", sortable:true, resizeable:true}, {key:"status", sortable:true, resizeable:true}, {key:"device_id", sortable:true, resizeable:true}, ]; var myDataSource = new YAHOO.util.DataSource(bookorders); myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY; myDataSource.responseSchema = { fields: ["test","test2","topic_id","status","device_id"] }; var myDataTable = new YAHOO.widget.DataTable("basic", myColumnDefs, myDataSource); It's print Data Error for some reason, what am I doing wrong? Thanks! I have tested the validity of the JSON at JSONLint and it says it is valid.

    Read the article

  • jqGrid Additional POST datas when deleting

    - by user300657
    I want to delete a row in the grid, but the grid always post's only the id and oper, I also want to post additional data. My jqgrid is something like : jQuery("#editgrid").jqGrid({ url:'autoJSON.php', datatype: "xml", colNames:['RowID','Asigurator','Cilindree','Persoana', 'Perioada', 'Pret'], colModel:[ {name:'rowID',index:'rowID', width:60, editable:true}, {name:'idAsigurator',index:'idAsigurator', width:100, editable:true,editoptions:{size:20}}, {name:'cilindree',index:'cilindree', width:90, editable:true,editoptions:{size:20}}, {name:'persoana',index:'persoana', width:300,editable:true,edittype:"select",editoptions:{value:"Persoana juridica:Persoana juridica;Pensionar:Pensionar;Persoana fizica:Persoana fizica"}}, {name:'perioada',index:'perioada', width:120, align:"right",edittype:"select",editable:true,editoptions:{value:"12 luni:12 luni;6 luni:6 luni"}}, {name:'pret',index:'pret', width:80, align:"right",editable:true,editoptions:{size:20}} ], width:900, height:600, pager: '#pagered', sortname: 'rowID', viewrecords: true, sortorder: "desc", caption:"Autoturisme", editurl:"autoPOST.php", }); jQuery("#editgrid").jqGrid('navGrid',"#pagered",{edit:true,add:true,del:true}); What should I do to access in autoPOST.php rowID also as a post variable. Thanks

    Read the article

  • Output of the following code

    - by terrific
    String s1 = "Amit"; //true String s2 = "Amit"; //true String s3 = new String("abcd"); //true String s4 = new String("abcd"); //false System.out.println(s1.equals(s2)); //true System.out.println((s1==s2)); //true System.out.println(s3.equals(s4)); //false System.out.println((s3==s4)); //false Assume it to be in main why the output of the above code is true true true false and not true true false false???

    Read the article

  • Extending jQuery Form Validation Script for new form fields

    - by user982124
    I have a simple HTML form that originally was a series of Questions (A1 to A5 and B1 to B3) with yes/no radio buttons like this: <tr> <td width="88%" valign="top" class="field_name_left">A1</td> <td width="12%" valign="top" class="field_data"> <input type="radio" name="CriteriaA1" value="Yes">Yes<input type="radio" name="CriteriaA1" value="No">No</td> </tr> The user could only answer either the A series of questions OR either the B series of questions, but not both. Also they must complete all questions in either the A or B series. I now have an additional series of questions - C1 to C6 - and need to extend my validation scripts to ensure the user enters either A, B or C and answers all questions within each series. My original script for just the A and B looks like this: $(function() { $("#editRecord").submit(function(){ // is anything checked? if(!checkEmpty()){ $("#error").html("Please check something before submitting"); //alert("nothing Checked"); return false; } // Only A _OR_ B if(isAorB()){ $("#error").html("Please complete A or B, not both"); //alert("please complete A or B, not both"); return false; }; // all A's or all B's if(allAorBChecked()){ $("#error").html("It appears you have not completed all questions"); //alert("missing data"); return false; }; if(haveNo()){ // we're going on, but sending "type = C" } //alert("all OK"); return true; }); }); function checkEmpty(){ var OK = false; $(":radio").each(function(){ if (this.checked){ OK = true; } }); return OK; } function isAorB(){ var OK = false; var Achecked = false; var Bchecked = false; $(":radio").each(function(){ var theChar=this.name.charAt(8); // if we have an A checked remember it if(theChar == "A" && this.checked && !Achecked){ Achecked = true; } if(Achecked && theChar == "B" && !Bchecked){ if(this.checked){ Bchecked = true; } } if (Achecked && Bchecked){ OK = true; } }); return OK; } function allAorBChecked(){ var notOK = false; var Achecked = false; $(":radio").each(function(){ // skip through to see if we're doing A's or B's var theChar=this.name.charAt(8); // check the A's if(theChar == "A" && this.checked && !Achecked){ Achecked = true; } }); if(Achecked){ // set the input to A $("#type").val("A"); // check _all_ a's are checked var thisName; var thisChecked = false; $(":radio").each(function(){ var theChar=this.name.charAt(8); var checked = this.checked; if (theChar == "A"){ if (this.name == thisName && !thisChecked){ // Yes wasn't checked - is No? if(!checked){ notOK = true; } } thisChecked = checked; thisName = this.name; } }); }else{ // set the input to B $("#type").val("B"); // check _all_ b's are checked var thisName; var thisChecked = false; $(":radio").each(function(){ var theChar=this.name.charAt(8); var checked = this.checked; if (theChar == "B"){ if (this.name == thisName && !thisChecked){ // A wasn't checked - is B? if(!checked){ notOK = true; } } thisChecked = checked; thisName = this.name; } }); } return notOK; } function haveNo(){ var thisName; var notOK = false; $(":radio").each(function(){ var checked = this.checked; if (this.name == thisName){ //Is this checked if(checked){ notOK = true; $("#type").val("C"); } } thisName = this.name; }); return notOK; } This worked well but I'm completely stuck at extending it to include the C series. I now have to check that the user hasn't answered any A and B, A and C and B and C questions. Everything I've tried fails to validate. Here's where I'm at right now with my new script: $(function() { $("#editRecord").submit(function(){ // is anything checked? if(!checkEmpty()){ $("#error").html("Please check something before submitting"); //alert("nothing Checked"); return false; } // Only A or B or C if(isAorBorC()){ $("#error").html("Please complete A or B or C, not both"); //alert("please complete A or B, not both"); return false; }; // all A's or all B's or all C's if(allAorBorCChecked()){ $("#error").html("It appears you have not completed all questions"); //alert("missing data"); return false; }; if(haveNo()){ // we're going on, but sending "type = C" } //alert("all OK"); return true; }); }); function checkEmpty(){ var OK = false; $(":radio").each(function(){ if (this.checked){ OK = true; } }); return OK; } function isAorBorC(){ var OK = false; var Achecked = false; var Bchecked = false; var Cchecked = false; $(":radio").each(function(){ var theChar=this.name.charAt(8); // if we have an A checked remember it if(theChar == "A" && this.checked && !Achecked){ Achecked = true; } if(theChar == "B" && this.checked && !Achecked){ Bchecked = true; } if(theChar == "C" && this.checked && !Achecked){ Cchecked = true; } if(Achecked && theChar == "B" && !Bchecked){ if(this.checked){ Bchecked = true; } } if(Achecked && theChar == "C" && !Cchecked){ if(this.checked){ Cchecked = true; } } if(Bchecked && theChar == "C" && !Cchecked){ if(this.checked){ Cchecked = true; } } if (Achecked && Bchecked){ OK = true; } if (Achecked && CBchecked){ OK = true; } if (Bchecked && Cchecked){ OK = true; } }); return OK; } function allAorBorCChecked(){ var notOK = false; var Achecked = false; $(":radio").each(function(){ // skip through to see if we're doing A's or B's var theChar=this.name.charAt(8); // check the A's if(theChar == "A" && this.checked && !Achecked){ Achecked = true; } }); if(Achecked){ // set the input to A $("#type").val("A"); // check _all_ a's are checked var thisName; var thisChecked = false; $(":radio").each(function(){ var theChar=this.name.charAt(8); var checked = this.checked; if (theChar == "A"){ if (this.name == thisName && !thisChecked){ // Yes wasn't checked - is No? if(!checked){ notOK = true; } } thisChecked = checked; thisName = this.name; } }); }elseif{ // set the input to B $("#type").val("B"); // check _all_ b's are checked var thisName; var thisChecked = false; $(":radio").each(function(){ var theChar=this.name.charAt(8); var checked = this.checked; if (theChar == "B"){ if (this.name == thisName && !thisChecked){ // A wasn't checked - is B? if(!checked){ notOK = true; } } thisChecked = checked; thisName = this.name; } }); } return notOK; } }else{ // set the input to C $("#type").val("C"); // check _all_ c's are checked var thisName; var thisChecked = false; $(":radio").each(function(){ var theChar=this.name.charAt(8); var checked = this.checked; if (theChar == "C"){ if (this.name == thisName && !thisChecked){ // A wasn't checked - is B? if(!checked){ notOK = true; } } thisChecked = checked; thisName = this.name; } }); } return notOK; } function haveNo(){ var thisName; var notOK = false; $(":radio").each(function(){ var checked = this.checked; if (this.name == thisName){ //Is this checked if(checked){ notOK = true; $("#type").val("C"); } } thisName = this.name; }); return notOK; } Anyone see what I'm doing wrong?

    Read the article

  • How to refer to the true 'body' of a page? [NOT iFrame body]

    - by Jim
    I have a script that create a new div element. Then, I want to append the div to the body of the page using appendChild method. The script is look like this : var div = document.createElement('div'); div.id = 'newdiv'; document.body.appendChild(div); Unfortunately, the div also appended to the body of iframes. So, my question is, how to refer to the true body of the document, not including the body of the iframes? That way, the div just appended once, to the "true body" of the document. Thanks before, and sorry if my english is bad. :-D

    Read the article

  • Get URL parameter function that gets value of url part or returns true if it's there but with no val

    - by LLer
    I'm using the following function to get a URL parameter. function gup(name, url) { name = name.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]'); var results = new RegExp('[\\?&]'+name+'=?([^&#]*)').exec(url || window.location.href); return results == null ? null : results[1]; } It works only if the parameter has a value, for example. gup('a', 'http://example.com/page.php?a=1&b=2'); will return 1. But if I try gup('a', 'http://example.com/page.php?a&b=2'); It returns null. I want it to return true because parameter "a" exists in that url, even though it has no value it's still there and gup() should return true. Could I get a bit of help rewriting this? I'm not that good with regex.

    Read the article

  • Why is it when I set "closeOnEscape" to false and then "closeOnEscape" to true jquery dialog escape

    - by chobo2
    Hi I am using jquery ui 1.8 and I have a model dialog that popups up and if a user clicks on a checkbox another one comes up. This requires them to say "yes" or "no" so I removed the "X" on the dialog and put closeOnEscape to false. However I noticed when I did that the model dialog underneath it would close when they hit escape. So now when the one that pops up when the checkbox is checked I disable closeOnEscape on the first dialog box. When they close it I enable again yet it does not work. I am not sure why $("#Dialog").dialog( "option", "closeOnEscape", true); I even do this in firebug. I just open my first dialog up Do this in firebugs console $("#Dialog").dialog( "option", "closeOnEscape", false); Then verify that escape is now disabled. I then try to enable it again $("#Dialog").dialog( "option", "closeOnEscape", true); Yet it never enables.

    Read the article

  • Get width of DataGridView Column When AutoGenerateColumns = true And It added dynomically?

    - by n H
    I want to get width of each column of DataGridView in codeBehinde after setting DataSource and before showing it to user: DataGridView dgv = new DataGridView(); dgv.AutoGenerateColumns = true; dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; dgv.AutoSize = true; dgv.DataSource = dc.Branches.ToList(); this.Controls.Add(dgv); //How to get Width of each Column Here?? var ColCount = dgv.Columns.Count; //return 0 ??

    Read the article

  • Why do we need to estimate the true position in Kalman filters?

    - by Kalla
    I am following a probably well-known tutorial about Kalman filter here From these lines of code: figure; plot(t,pos, t,posmeas, t,poshat); grid; xlabel('Time (sec)'); ylabel('Position (feet)'); title('Figure 1 - Vehicle Position (True, Measured, and Estimated)') I understand that x is the true position, y is measured position, xhat is estimated position. Then, if we can compute x (this code: x = a * x + b * u + ProcessNoise;), why do we need to estimated x anymore?

    Read the article

  • How to check the status (True/False) in a grid view on rowdatabound event?

    - by NayeemKhan
    Hi all, I have a table with three columns (ProdID,ProdName,Status). I m fetching that into a dataSet and binding that to my gridview. I have a very basic and simple rowdatabound event like this : protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if (e.Row.Cells[2].Text == "False") { e.Row.BackColor = System.Drawing.Color.PaleVioletRed; } } } But when i see my 3rd column (Status), it is converted to a checkbox, may be becz its containing only 'True' or 'False'. Also in my if condition : if (e.Row.Cells[3].Text == "False") the text value is showing this : "" Can anybody suggest me, how can i compare my status against True or False in my if condition.

    Read the article

  • Has anyone achieved true differential sync with rsync in ESXi?

    - by Julius
    Berate me later on the fact that I'm using the service console to do anything in ESXi... I've got a working rsync binary (v3.0.4) that I can use in ESXi 4.1U1. I tend to use rsync over cp when copying VM's or backups from one local datastore to another local datastore. I've used rsync to copy data from one ESXi box to another but that was just for small files. In now trying to do true differential syncs of backups taken via ghettoVCB between my primary ESXi machine and a secondary one. But even when I do this locally (one datastore to another datastore on the same ESXi machine) rsync appears to copy the files in their entirety. I've got two VMDK's totally 80GB in size, and rsync still takes anywhere between 1 and 2 hours but the VMDK's aren't growing that much daily. Below is the rsync command I'm executing. I am copying locally because ultimately these files will get copied onto a datastore created from a LUN on a remote system. Its not an rsync that'll be serviced by an rsync daemon on a remote system. rsync -avPSI VMBACKUP_2011-06-10_02-27-56/* VMBACKUP_2011-06-01_06-37-11/ --stats --itemize-changes --existing --modify-window=2 --no-whole-file sending incremental file list >f..t...... VM-flat.vmdk 42949672960 100% 15.06MB/s 0:45:20 (xfer#1, to-check=5/6) >f..t...... VM.vmdk 556 100% 4.24kB/s 0:00:00 (xfer#2, to-check=4/6) >f..t...... VM.vmx 3327 100% 25.19kB/s 0:00:00 (xfer#3, to-check=3/6) >f..t...... VM_1-flat.vmdk 42949672960 100% 12.19MB/s 0:56:01 (xfer#4, to-check=2/6) >f..t...... VM_1.vmdk 558 100% 2.51kB/s 0:00:00 (xfer#5, to-check=1/6) >f..t...... STATUS.ok 30 100% 0.02kB/s 0:00:01 (xfer#6, to-check=0/6) Number of files: 6 Number of files transferred: 6 Total file size: 85899350391 bytes Total transferred file size: 85899350391 bytes Literal data: 2429682778 bytes Matched data: 83469667613 bytes File list size: 129 File list generation time: 0.001 seconds File list transfer time: 0.000 seconds Total bytes sent: 2432530094 Total bytes received: 5243054 sent 2432530094 bytes received 5243054 bytes 295648.92 bytes/sec total size is 85899350391 speedup is 35.24 Is this because ESXi is itself making so many changes to the VMDK's that as far as rsync is concerned the entire file has to be retransmitted? Has anyone actually achieved actual diff sync with ESXi?

    Read the article

  • where is this function getting its values from

    - by user295189
    I have the JS file below that I am working on and I have a need to know this specific function pg.getRecord_Response = function(){ } within the file. I need to know where are the values are coming from in this function for example arguments[0].responseText? I am new to javascript so any help will be much appreciated. Thanks var pg = new Object(); var da = document.body.all; // ===== - EXPRESS BUILD [REQUEST] - ===== // pg.expressBuild_Request = function(){ var n = new Object(); n.patientID = request.patientID; n.encounterID = request.encounterID; n.flowSheetID = request.flowSheetID; n.encounterPlan = request.encounterPlan; n.action = "/location/diagnosis/dsp_expressBuild.php"; n.target = popWinCenterScreen("/common/html/empty.htm", 619, 757, ""); myLocationDB.PostRequest(n); } // ===== - EXPRESS BUILD [RESPONSE] - ===== // pg.expressBuild_Response = function(){ pg.records.showHiddenRecords = 0; pg.loadRecords_Request(arguments.length ? arguments[0] : 0); } // ===== - GET RECORD [REQUEST] - ===== // pg.getRecord_Request = function(){ if(pg.records.lastSelected){ pg.workin(true); pg.record.recordID = pg.records.lastSelected.i; var n = new Object(); n.noheaders = 1; n.recordID = pg.record.recordID; myLocationDB.Ajax.Post("/location/diagnosis/get_record.php", n, pg.getRecord_Response); } else { pg.buttons.btnOpen.disable(true); } } // ===== - GET RECORD [RESPONSE] - ===== // pg.getRecord_Response = function(){ //alert(arguments[0].responseText); if(arguments.length && arguments[0].responseText){ alert(arguments[0].responseText); // Refresh PQRI grid when encounter context if(request.encounterID && window.parent.frames['main']){ window.parent.frames['main'].pg.loadQualityMeasureRequest(); } var rec = arguments[0].responseText.split(pg.delim + pg.delim); if(rec.length == 20){ // validate record values rec[0] = parseInt(rec[0]); rec[3] = parseInt(rec[3]); rec[5] = parseInt(rec[5]); rec[6] = parseInt(rec[6]); rec[7] = parseInt(rec[7]); rec[8] = parseInt(rec[8]); rec[9] = parseInt(rec[9]); rec[10] = parseInt(rec[10]); rec[11] = parseInt(rec[11]); rec[12] = parseInt(rec[12]); rec[15] = parseInt(rec[15]); // set record state pg.recordState = { recordID: pg.record.recordID, codeID: rec[0], description: rec[2], assessmentTypeID: rec[3], type: rec[4], onsetDateYear: rec[5], onsetDateMonth: rec[6], onsetDateDay: rec[7], onsetDateIsApproximate: rec[8], resolveDateYear: rec[9], resolveDateMonth: rec[10], resolveDateDay: rec[11], resolveDateIsApproximate: rec[12], commentsCount: rec[15], comments: rec[16] } // set record view pg.record.code.codeID = pg.recordState.codeID; pg.record.code.value = rec[1]; pg.record.description.value = rec[2]; for(var i=0; i<pg.record.type.options.length; i++){ if(pg.record.type.options[i].value == rec[4]){ pg.record.type.selectedIndex = i; break; } } for(var i=0; i<pg.record.assessmentType.options.length; i++){ if(pg.record.assessmentType.options[i].value == rec[3]){ pg.record.assessmentType.selectedIndex = i; break; } } if(rec[5]){ if(rec[6] && rec[7]){ pg.record.onsetDateType.selectedIndex = 0; pg.record.onsetDate.value = rec[6] + "/" + rec[7] + "/" + rec[5]; pg.record.onsetDate.format(); } else { pg.record.onsetDateType.selectedIndex = 1; pg.record.onsetDateMonth.selectedIndex = rec[6]; for(var i=0; i<pg.record.onsetDateYear.options.length; i++){ if(pg.record.onsetDateYear.options[i].value == rec[5]){ pg.record.onsetDateYear.selectedIndex = i; break; } } if(rec[8]) pg.record.chkOnsetDateIsApproximate.checked = true; } } else { pg.record.onsetDateType.selectedIndex = 2; } if(rec[9]){ if(rec[10] && rec[11]){ pg.record.resolveDateType.selectedIndex = 0; pg.record.resolveDate.value = rec[10] + "/" + rec[11] + "/" + rec[9]; pg.record.resolveDate.format(); } else { pg.record.resolveDateType.selectedIndex = 1; pg.record.resolveDateMonth.selectedIndex = rec[10]; for(var i=0; i<pg.record.resolveDateYear.options[i].length; i++){ if(pg.record.resolveDateYear.options.value == rec[9]){ pg.record.resolveDateYear.selectedIndex = i; break; } } if(rec[12]) pg.record.chkResolveDateIsApproximate.checked = true; } } else { pg.record.resolveDateType.selectedIndex = 2; } pg.record.lblCommentCount.innerHTML = rec[15]; pg.record.comments.value = rec[16]; pg.record.lblUpdatedBy.innerHTML = "* Last updated by " + rec[13] + " on " + rec[14]; pg.record.lblUpdatedBy.title = "Updated by: " + rec[13] + "\nUpdated on: " + rec[14]; pg.record.linkedNotes.setData(rec[18]); pg.record.linkedOrders.setData(rec[19]); pg.record.updates.setData(rec[17]); return; } } alert("An error occured while attempting to retrieve\ndetails for record #" + pg.record.recordID + ".\n\nPlease contact support if this problem persists.\nWe apologize for the inconvenience."); pg.hideRecordView(); } // ===== - HIDE COMMENTS VIEW - ===== // pg.hideCommentsView = function(){ pg.recordComments.style.left = ""; pg.recordComments.disabled = true; pg.recordComments.comments.value = ""; pg.record.disabled = false; pg.record.style.zIndex = 5500; } // ===== - HIDE code SEARCH - ===== // pg.hidecodeSearch = function(){ pg.codeSearch.style.left = ""; pg.codeSearch.disabled = true; pg.record.disabled = false; pg.record.style.zIndex = 5500; } // ===== - HIDE RECORD - ===== // pg.hideRecord = function(){ if(arguments.length){ pg.loadRecords_Request(); } else if(pg.records.lastSelected){ var n = new Object(); n.recordTypeID = 11; n.patientID = request.patientID; n.recordID = pg.records.lastSelected.i; n.action = "/location/hideRecord/dsp_hideRecord.php"; n.target = popWinCenterScreen("/common/html/empty.htm", 164, 476); myLocationDB.PostRequest(n); } } // ===== - HIDE RECORD VIEW - ===== // pg.hideRecordView = function(){ pg.record.style.left = ""; pg.record.disabled = true; // reset record grids pg.record.updates.state = "NO_RECORDS"; pg.record.linkedNotes.state = "NO_RECORDS"; pg.record.linkedOrders.state = "NO_RECORDS"; // reset linked record tabs pg.record.tabs[0].click(); pg.record.tabs[1].disable(true); pg.record.tabs[2].disable(true); pg.record.tabs[1].all[1].innerHTML = "Notes"; pg.record.tabs[2].all[1].innerHTML = "Orders"; // reset record state pg.recordState = null; // reset record view pg.record.recordID = 0; pg.record.code.value = ""; pg.record.code.codeID = 0; pg.record.description.value = ""; pg.record.type.selectedIndex = 0; pg.record.assessmentType.selectedIndex = 0; pg.record.onsetDateType.selectedIndex = 0; pg.record.chkOnsetDateIsApproximate.checked = false; pg.record.resolveDateType.selectedIndex = 0; pg.record.chkResolveDateIsApproximate.checked = false; pg.record.lblCommentCount.innerHTML = 0; pg.record.comments.value = ""; pg.record.lblUpdatedBy.innerHTML = ""; pg.record.lblUpdatedBy.title = ""; pg.record.updateComment = ""; pg.recordComments.comments.value = ""; pg.record.active = false; pg.codeSearch.newRecord = true; pg.blocker.className = ""; pg.workin(false); } // ===== - HIDE UPDATE VIEW - ===== // pg.hideUpdateView = function(){ pg.recordUpdate.style.left = ""; pg.recordUpdate.disabled = true; pg.recordUpdate.type.value = ""; pg.recordUpdate.onsetDate.value = ""; pg.recordUpdate.description.value = ""; pg.recordUpdate.resolveDate.value = ""; pg.recordUpdate.assessmentType.value = ""; pg.record.disabled = false; pg.record.btnViewUpdate.setState(); pg.record.style.zIndex = 5500; } // ===== - INIT - ===== // pg.init = function(){ var tab = 1; pg.delim = String.fromCharCode(127); pg.subDelim = String.fromCharCode(1); pg.blocker = da.blocker; pg.hourglass = da.hourglass; pg.pageContent = da.pageContent; pg.blocker.shim = da.blocker_shim; pg.activeTip = da.activeTip; pg.activeTip.anchor = null; pg.activeTip.shim = da.activeTip_shim; // PAGE TITLE pg.pageTitle = da.pageTitle; // TOTAL RECORDS pg.totalRecords = da.totalRecords[0]; // START RECORD pg.startRecord = da.startRecord[0]; pg.startRecord.onchange = function(){ pg.records.startRecord = this.value; pg.loadRecords_Request(); } // RECORD PANEL pg.recordPanel = myLocationDB.RecordPanel(pg.pageContent.all.recordPanel); for(var i=0; i<pg.recordPanel.buttons.length; i++){ if(pg.recordPanel.buttons[i].orderBy){ pg.recordPanel.buttons[i].onclick = pg.sortRecords; } } // RECORDS GRIDVIEW pg.records = pg.recordPanel.all.grid; alert(pg.recordPanel.all.grid); pg.records.sortOrder = "DESC"; pg.records.lastExpanded = null; pg.records.attachEvent("onrowclick", pg.record_click); pg.records.orderBy = pg.recordPanel.buttons[0].orderBy; pg.records.attachEvent("onrowmouseout", pg.record_mouseOut); pg.records.attachEvent("onrowdblclick", pg.getRecord_Request); pg.records.attachEvent("onrowmouseover", pg.record_mouseOver); pg.records.attachEvent("onstateready", pg.loadRecords_Response); // BUTTON - TOGGLE HIDDEN RECORDS pg.btnHiddenRecords = myLocationDB.Custom.ImageButton(3, 751, 19, 19, "/common/images/hide.gif", 1, 1, "", "", da.pageContent); pg.btnHiddenRecords.setTitle("Show hidden records"); pg.btnHiddenRecords.onclick = pg.toggleHiddenRecords; pg.btnHiddenRecords.setState = function(){ this.disable(!pg.records.totalHiddenRecords); } // code SEARCH SUBWIN pg.codeSearch = da.subWin_codeSearch; pg.codeSearch.newRecord = true; pg.codeSearch.searchType = "code"; pg.codeSearch.searchFavorites = true; pg.codeSearch.onkeydown = function(){ if(window.event && window.event.keyCode && window.event.keyCode == 113){ if(pg.codeSearch.searchType == "DESCRIPTION"){ pg.codeSearch.searchType = "code"; pg.codeSearch.lblSearchType.innerHTML = "ICD-9 Code"; } else { pg.codeSearch.searchType = "DESCRIPTION"; pg.codeSearch.lblSearchType.innerHTML = "Description"; } pg.searchcodes_Request(); } } // SEARCH TYPE pg.codeSearch.lblSearchType = pg.codeSearch.all.lblSearchType; // SEARCH STRING pg.codeSearch.searchString = pg.codeSearch.all.searchString; pg.codeSearch.searchString.tabIndex = 1; pg.codeSearch.searchString.onfocus = function(){ this.select(); } pg.codeSearch.searchString.onblur = function(){ this.value = this.value.trim(); } pg.codeSearch.searchString.onkeydown = function(){ if(window.event && window.event.keyCode && window.event.keyCode == 13){ pg.searchcodes_Request(); } } // -- "SEARCH" pg.codeSearch.btnSearch = pg.codeSearch.all.btnSearch; pg.codeSearch.btnSearch.tabIndex = 2; pg.codeSearch.btnSearch.disable = myLocationDB.Disable; pg.codeSearch.btnSearch.onclick = pg.searchcodes_Request; pg.codeSearch.btnSearch.baseTitle = "Search diagnosis codes"; pg.codeSearch.btnSearch.setState = function(){ pg.codeSearch.btnSearch.disable(pg.codeSearch.searchString.value.trim().length < 2); } pg.codeSearch.searchString.onkeyup = pg.codeSearch.btnSearch.setState; // START RECORD / TOTAL RECORDS pg.codeSearch.startRecord = pg.codeSearch.all.startRecord; pg.codeSearch.totalRecords = pg.codeSearch.all.totalRecords; pg.codeSearch.startRecord.onchange = function(){ pg.codeSearch.records.startRecord = this.value; pg.searchcodes_Request(); } // RECORD PANEL pg.codeSearch.recordPanel = myLocationDB.RecordPanel(pg.codeSearch.all.recordPanel); pg.codeSearch.recordPanel.buttons[0].onclick = pg.sortcodeResults; pg.codeSearch.recordPanel.buttons[1].onclick = pg.sortcodeResults; // DATA GRIDVIEW pg.codeSearch.records = pg.codeSearch.all.grid; pg.codeSearch.records.orderBy = "code"; pg.codeSearch.records.attachEvent("onrowdblclick", pg.updatecode); pg.codeSearch.records.attachEvent("onstateready", pg.searchcodes_Response); // BUTTON - "CANCEL" pg.codeSearch.btnCancel = pg.codeSearch.all.btnCancel; pg.codeSearch.btnCancel.tabIndex = 4; pg.codeSearch.btnCancel.onclick = pg.hidecodeSearch; pg.codeSearch.btnCancel.title = "Close this search area"; // SEARCH FAVORITES / ALL pg.codeSearch.optSearch = myLocationDB.InputButton(pg.codeSearch.all.optSearch); pg.codeSearch.optSearch[0].onclick = function(){ if(pg.codeSearch.searchFavorites){ pg.codeSearch.searchString.focus(); } else { pg.codeSearch.searchFavorites = true; pg.searchcodes_Request(); } } pg.codeSearch.optSearch[1].onclick = function(){ if(pg.codeSearch.searchFavorites){ pg.codeSearch.searchFavorites = false; pg.searchcodes_Request(); } else { pg.codeSearch.searchString.focus(); } } // -- "USE SELECTED" pg.codeSearch.btnUseSelected = pg.codeSearch.all.btnUseSelected; pg.codeSearch.btnUseSelected.tabIndex = 3; pg.codeSearch.btnUseSelected.onclick = pg.updatecode; pg.codeSearch.btnUseSelected.disable = myLocationDB.Disable; pg.codeSearch.btnUseSelected.baseTitle = "Use the selected diagnosis code"; pg.codeSearch.btnUseSelected.setState = function(){ pg.codeSearch.btnUseSelected.disable(!pg.codeSearch.records.lastSelected); } pg.codeSearch.records.attachEvent("onrowclick", pg.codeSearch.btnUseSelected.setState); // RECORD STATE pg.recordState = null; // RECORD SUBWIN pg.record = da.subWin_record; pg.record.recordID = 0; pg.record.active = false; pg.record.updateComment = ""; // -- TABS pg.record.tabs = myLocationDB.TabCollection( pg.record.all.tab, function(){ if(pg.record.tabs[0].all[0].checked){ pg.record.btnOpen.style.display = "none"; pg.record.chkSelectAll.hitArea.style.display = "none"; pg.record.btnSave.style.display = "block"; pg.record.lblUpdatedBy.style.display = "block"; pg.record.pnlRecord_shim.style.display = "none"; } else { pg.record.pnlRecord_shim.style.display = "block"; pg.record.btnSave.style.display = "none"; pg.record.lblUpdatedBy.style.display = "none"; pg.record.btnOpen.setState(); pg.record.btnOpen.style.display = "block"; if(pg.record.tabs[2].all[0].checked){ pg.record.chkSelectAll.hitArea.style.display = "none"; //pg.record.btnViewLabs.setState(); //pg.record.btnViewLabs.style.display = "block"; } else { pg.record.chkSelectAll.setState(); pg.record.chkSelectAll.hitArea.style.display = "block"; //pg.record.btnViewLabs.style.display = "none"; } } } ); pg.record.tabs[1].disable(true); pg.record.tabs[2].disable(true); pg.record.pnlRecord_shim = pg.record.all.pnlRecord_shim; pg.record.code = pg.record.all.code; pg.record.code.codeID = 0; pg.record.code.tabIndex = -1; // -- CHANGE code pg.record.btnChangecode = myLocationDB.Custom.ImageButton(6, 107, 22, 22, "/common/images/edit.gif", 2, 2, "", "", pg.record.all.pnlRecord); pg.record.btnChangecode.tabIndex = 1; pg.record.btnChangecode.onclick = pg.showcodeSearch; pg.record.btnChangecode.title = "Change the diagnosis code for this problem"; pg.record.description = pg.record.all.description; pg.record.description.tabIndex = 2; pg.record.type = pg.record.all.type; pg.record.type.tabIndex = 3; pg.record.assessmentType = pg.record.all.assessmentType; pg.record.assessmentType.tabIndex = 9; // ONSET DATE pg.record.onsetDateType = pg.record.all.onsetDateType; pg.record.onsetDateType.tabIndex = 4; pg.record.onsetDateType.onchange = pg.record.onsetDateType.setState = function(){ switch(this.selectedIndex){ case 1: // PARTIAL pg.record.chkOnsetDateIsApproximate.disable(false); pg.record.onsetDate.style.visibility = "hidden"; pg.record.onsetDateUnknown.style.visibility = "hidden"; pg.record.onsetDate.datePicker.style.visibility = "hidden"; pg.record.onsetDateMonth.style.visibility = "visible"; pg.record.onsetDateYear.style.visibility = "visible"; break; case 2: // UNKNOWN pg.record.chkOnsetDateIsApproximate.disable(true); pg.record.onsetDate.style.visibility = "hidden"; pg.record.onsetDateYear.style.visibility = "hidden"; pg.record.onsetDateMonth.style.visibility = "hidden"; pg.record.onsetDate.datePicker.style.visibility = "hidden"; pg.record.onsetDateUnknown.style.visibility = "visible"; break; default: // "WHOLE" pg.record.chkOnsetDateIsApproximate.disable(true); pg.record.onsetDateMonth.style.visibility = "hidden"; pg.record.onsetDateYear.style.visibility = "hidden"; pg.record.onsetDateUnknown.style.visibility = "hidden"; pg.record.onsetDate.style.visibility = "visible"; pg.record.onsetDate.datePicker.style.visibility = "visible"; break; } } pg.record.onsetDate = myLocationDB.Custom.DateInput(30, 364, 80, pg.record.all.pnlRecord, 1, 1, 0, params.todayDate, 1); pg.record.onsetDate.tabIndex = 5; pg.record.onsetDate.style.textAlign = "LEFT"; pg.record.onsetDate.calendar.style.zIndex = 6000; pg.record.onsetDate.datePicker.style.left = "448px"; pg.record.onsetDate.setDateRange(params.birthDate, params.todayDate); pg.record.onsetDateYear = pg.record.all.onsetDateYear; pg.record.onsetDateYear.tabIndex = 6; pg.record.onsetDateMonth = pg.record.all.onsetDateMonth pg.record.onsetDateMonth.tabIndex = 7; pg.record.onsetDateUnknown = pg.record.all.onsetDateUnknown; pg.record.onsetDateUnknown.tabIndex = 8; pg.record.chkOnsetDateIsApproximate = myLocationDB.InputButton(pg.record.all.chkOnsetDateIsApproximate); pg.record.chkOnsetDateIsApproximate.setTitle("Onset date is approximate"); pg.record.chkOnsetDateIsApproximate.disable(true); // RESOLVE DATE pg.record.lblResolveDate = pg.record.all.lblResolveDate; pg.record.resolveDateType = pg.record.all.resolveDateType; pg.record.resolveDateType.tabIndex = 10; pg.record.resolveDateType.lastSelectedIndex = 0; pg.record.resolveDateType.setState = function(){ switch(this.selectedIndex){ case 1: // PARTIAL pg.record.chkResolveDateIsApproximate.disable(false); pg.record.resolveDate.style.visibility = "hidden"; pg.record.resolveDateUnknown.style.visibility = "hidden"; pg.record.resolveDate.datePicker.style.visibility = "hidden"; pg.record.resolveDateMonth.style.visibility = "visible"; pg.record.resolveDateYear.style.visibility = "visible"; break; case 2: // UNKNOWN pg.record.chkResolveDateIsApproximate.disable(true); pg.record.resolveDate.style.visibility = "hidden"; pg.record.resolveDateYear.style.visibility = "hidden"; pg.record.resolveDateMonth.style.visibility = "hidden"; pg.record.resolveDate.datePicker.style.visibility = "hidden"; pg.record.resolveDateUnknown.style.visibility = "visible"; break; default: // "WHOLE" pg.record.chkResolveDateIsApproximate.disable(true); pg.record.resolveDateMonth.style.visibility = "hidden"; pg.record.resolveDateYear.style.visibility = "hidden"; pg.record.resolveDateUnknown.style.visibility = "hidden"; pg.record.resolveDate.style.visibility = "visible"; pg.record.resolveDate.datePicker.style.visibility = "visible"; break; } } pg.record.resolveDateType.onchange = function(){ this.lastSelectedIndex = this.selectedIndex; this.setState(); } pg.record.resolveDate = myLocationDB.Custom.DateInput(55, 364, 80, pg.record.all.pnlRecord, 1, 1, 0, params.todayDate, 1); pg.record.resolveDate.tabIndex = 11; pg.record.resolveDate.style.textAlign = "LEFT"; pg.record.resolveDate.calendar.style.zIndex = 6000; pg.record.resolveDate.datePicker.style.left = "448px"; pg.record.resolveDate.setDateRange(params.birthDate, params.todayDate); pg.record.resolveDate.setState = function(){ if(pg.record.assessmentType.value == 15){ pg.record.chkResolveDateIsApproximate.disable(pg.record.resolveDateType.value != "PARTIAL"); pg.record.resolveDate.disabled = false; pg.record.lblResolveDate.disabled = false; pg.record.resolveDateType.selectedIndex = pg.record.resolveDateType.lastSelectedIndex; pg.record.resolveDateType.setState(); pg.record.resolveDate.datePicker.disable(false); pg.record.resolveDateType.disabled = false; pg.record.resolveDateYear.disabled = false; pg.record.resolveDateMonth.disabled = false; pg.record.resolveDateUnknown.disabled = false; } else { pg.record.resolveDate.datePicker.disable(true); pg.record.chkResolveDateIsApproximate.disable(true); pg.record.resolveDateType.selectedIndex = 2; pg.record.resolveDateType.setState(); pg.record.resolveDate.disabled = true; pg.record.lblResolveDate.disabled = true; pg.record.resolveDateType.disabled = true; pg.record.resolveDateYear.disabled = true; pg.record.resolveDateMonth.disabled = true; pg.record.resolveDateUnknown.disabled = true; } } pg.record.assessmentType.onchange = pg.record.resolveDate.setState; pg.record.resolveDateYear = pg.record.all.resolveDateYear; pg.record.resolveDateYear.tabIndex = 11; pg.record.resolveDateMonth = pg.record.all.resolveDateMonth pg.record.resolveDateMonth.tabIndex = 12; pg.record.resolveDateUnknown = pg.record.all.resolveDateUnknown; pg.record.resolveDateUnknown.tabIndex = 13; pg.record.chkResolveDateIsApproximate = myLocationDB.InputButton(pg.record.all.chkResolveDateIsApproximate); pg.record.chkResolveDateIsApproximate.setTitle("Resolve date is approximate"); pg.record.chkResolveDateIsApproximate.disable(true); // -- UPDATES pg.record.updates = pg.record.all.pnlUpdates.all.grid; pg.record.lblUpdateCount = pg.record.all.lblUpdateCount; pg.record.updates.attachEvent("onstateready", pg.showRecordView); pg.record.updates.attachEvent("onrowdblclick", pg.showUpdateView); // -- "VIEW SELECTED" pg.record.btnViewUpdate = myLocationDB.PanelButton(pg.record.all.btnViewUpdate); pg.record.btnViewUpdate.setTitle("View details for the selected problem update"); pg.record.btnViewUpdate.onclick = pg.showUpdateView; pg.record.btnViewUpdate.setState = function(){ pg.record.btnViewUpdate.disable(!pg.record.updates.lastSelected); } pg.record.updates.attachEvent("onrowclick", pg.record.btnViewUpdate.setState); // -- COMMENTS pg.record.comments = pg.record.all.comments; pg.record.pnlComments = pg.record.all.pnlComments; pg.record.lblCommentCount = pg.record.all.lblCommentCount; // -- UPDATE COMMENTS pg.record.btnUpdateComments = myLocationDB.PanelButton(pg.record.all.btnUpdateComments); pg.record.btnUpdateComments.onclick = pg.showCommentView; pg.record.btnUpdateComments.title = "Update this record's comments"; // -- LINKED NOTES pg.record.linkedNotes = pg.record.all.linkedNotes.all.grid; pg.record.linkedNotes.attachEvent("onrowclick", pg.linkedRecordClick); pg.record.linkedNotes.attachEvent("onrowdblclick", pg.openLinkedNote); pg.record.linkedNotes.attachEvent("onstateready", pg.setLinkedNotes_Count); // -- LINKED ORDERS pg.record.linkedOrders = pg.record.all.linkedOrders.all.grid; pg.record.linkedOrders.attachEvent("onrowclick", pg.linkedRecordClick); pg.record.linkedOrders.attachEvent("onrowdblclick", pg.openLinkedOrder); pg.record.linkedOrders.attachEvent("onstateready", pg.setLinkedOrders_Count); // -- "CLOSE" pg.record.btnClose = pg.record.all.btnClose; pg.record.btnClose.tabIndex = 15; pg.record.btnClose.onclick = pg.hideRecordView; pg.record.btnClose.title = "Close this record panel"; // -- LAST UPDATED BY pg.record.lblUpdatedBy = pg.record.all.lblUpdatedBy; // -- "SELECT ALL" pg.record.chkSelectAll = myLocationDB.InputButton(pg.record.all.chkSelectAll); pg.record.chkSelectAll.onclick = function(){ if(pg.record.tabs[1].all[0].checked){ if(pg.record.chkSelectAll.checked){ pg.record.linkedNotes.selectAll(); } else { pg.record.linkedNotes.deselectAll(); } } else { if(pg.record.chkSelectAll.checked){ pg.record.linkedOrders.selectAll(); } else { pg.record.linkedOrders.deselectAll(); } } pg.record.btnOpen.setState(); //pg.record.btnViewLabs.setState(); } pg.record.chkSelectAll.setState = function(){ if(pg.record.tabs[1].all[0].checked){ pg.record.chkSelectAll.checked = pg.record.linkedNotes.selectedRows.length == pg.record.linkedNotes.rows.length; } else { pg.record.chkSelectAll.checked = pg.record.linkedOrders.selectedRows.length == pg.record.linkedOrders.rows.length; } } // -- "OPEN SELECTED" pg.record.btnOpen = pg.record.all.btnOpenSelected; pg.record.btnOpen.tabIndex = 14; pg.record.btnOpen.disable = myLocationDB.Disable; pg.record.btnOpen.title = "Open the selected record"; pg.record.btnOpen.onclick = function(){ if(pg.record.tabs[1].all[0].checked){ pg.openLinkedNote(); } else if(pg.record.tabs[2].all[0].checked){ pg.openLinkedOrder(); } else { pg.record.btnOpen.disable(true); } } pg.record.btnOpen.setState = function(){ if(pg.record.tabs[1].all[0].checked){ pg.record.btnOpen.disable(!pg.record.linkedNotes.lastSelected); } else if(pg.record.tabs[2].all[0].checked){ pg.record.btnOpen.disable(pg.record.linkedOrders.selectedRows.length != 1); } else { pg.record.btnOpen.disable(true); } } // -- "SAVE" pg.record.btnSave = pg.record.all.btnSave; pg.record.btnSave.tabIndex = 14; pg.record.btnSave.onclick = pg.updateRecord_Request; pg.record.btnSave.title = "Save changes to this record"; // RECORD UPDATE SUBWIN pg.recordUpdate = da.subWin_update; pg.recordUpdate.lblUpdatedBy = pg.recordUpdate.all.lblUpdatedBy; pg.recordUpdate.lblUpdateDTS = pg.recordUpdate.all.lblUpdateDTS; pg.recordUpdate.type = pg.recordUpdate.all.type; pg.recordUpdate.onsetDate = pg.recordUpdate.all.onsetDate; pg.recordUpdate.description = pg.recordUpdate.all.description; pg.recordUpdate.resolveDate = pg.recordUpdate.all.resolveDate; pg.recordUpdate.assessmentType = pg.recordUpdate.all.assessmentType; // -- "CLOSE" pg.recordUpdate.btnClose = pg.recordUpdate.all.btnClose; pg.recordUpdate.btnClose.tabIndex = 1; pg.recordUpdate.btnClose.onclick = pg.hideUpdateView; pg.recordUpdate.btnClose.title = "Close this sub-window"; // COMMENTS SUBWIN pg.recordComments = da.subWin_comments; pg.recordComments.comments = pg.recordComments.all.updateComments; pg.recordComments.comment

    Read the article

  • Solving File Upload Cancel Issue

    - by Frank Nimphius
    In Oracle JDeveloper 11g R1 (I did not test 11g R2) the file upload component is submitted even if users click a cancel button with immediate="true" set. Usually, immediate="true" on a command button by-passes all modle updates, which would make you think that the file upload isn't processed either. However, using a form like shown below, pressing the cancel button has no effect in that the file upload is not suppressed. <af:form id="f1" usesUpload="true">        <af:inputFile label="Choose file" id="fileup" clientComponent="true"                 value="#{FileUploadBean.file}"  valueChangeListener="#{FileUploadBean.onFileUpload}">   </af:inputFile>   <af:commandButton text="Submit" id="cb1" partialSubmit="true"                     action="#{FileUploadBean.onInputFormSubmit}"/>   <af:commandButton text="cancel" id="cb2" immediate="true"/> </af:form> The solution to this problem is a change of the event root, which you can achieve either by setting i) partialSubmit="true" on the command button, or by surrounding the form parts that should not be submitted when the cancel button is pressed with an ii) af:subform tag. i) partialSubmit solution <af:form id="f1" usesUpload="true">      <af:inputFile .../>   <af:commandButton text="Submit" .../>   <af:commandButton text="cancel" immediate="true" partialSubmit="true" .../> </af:form> ii) subform solution <af:form id="f1" usesUpload="true">   <af:subform id="sf1">     <af:inputFile ... />     <af:commandButton text="Submit" ..."/>   </af:subform>   <af:commandButton text="cancel" immediate="true" .../> </af:form> Note that the af:subform surrounds the input form parts that you want to submit when the submit button is pressed. By default, the af:subform only submits its contained content if the submit issued from within.

    Read the article

  • Is there really a need for encryption to have true wireless security? [closed]

    - by Cawas
    I welcome better key-wording here, both on tags and title. I'm trying to conceive a free, open and secure network environment that would work anywhere, from big enterprises to small home networks of just 1 machine. I think since wireless Access Points are the most, if not only, true weak point of a Local Area Network (let's not consider every other security aspect of having internet) there would be basically two points to consider here: Having an open AP for anyone to use the internet through Leaving the whole LAN also open for guests to be able to easily read (only) files on it, and even a place to drop files on Considering these two aspects, once everything is done properly... What's the most secure option between having that, or having just an encrypted password-protected wifi? Of course "both" would seem "more secure". But it shouldn't actually be anything substantial. That's the question, but I think it may need more elaborating on. If you don't think so, please feel free to skip the next (long) part. Elaborating more on the two aspects ... I've always had the feeling using any kind of the so called "wireless security" methods is actually a bad design. I'm talking mostly about encrypting and pass-phrasing (which are actually two different concepts), since I won't even consider hiding SSID and mac filtering. I understand it's a natural way of thinking. With cable networking nobody can access the network unless they have access to the physical cable, so you're "secure" in the physical way. In a way, encrypting is for wireless what building walls is for the cables. And giving pass-phrases would be adding a door with a key. But the cabling without encryption is also insecure. If someone plugin all the data is right there. So, while I can see the use for encrypting data, I don't think it's a security measure in wireless networks. It's wasting resources for too little gain. I believe we should encrypt only sensitive data regardless of wires. That's already done with HTTPS, so I don't really need to encrypt my torrents, for instance. They're torrents, they are meant to be freely shared! As for using passwords, they should be added to the users, always. Not to wifi. For securing files, truly, best solution is backup. Sure all that doesn't happen that often, but I won't consider the most situations where people just don't care. I think there are enough situations where we actually use passwords on our OS users, so let's go with that in mind. I keep promoting the Fonera concept as an instance. It opens up a free wifi port, if you choose so, and anyone can connect to the internet through that, without having any access to your LAN. It also uses a QoS which will never let your bandwidth drop from that public usage. That's security, and it's open. But it's lacking the second aspect. I'll probably be bashed for promoting the non-usage of WPA 2 with AES or whatever, but I wanted to know from more experienced (super) users out there: what do you think?

    Read the article

  • How to insert sub root node in xml file

    - by pravakar
    Hi guys hope all are doing good. I want to create one sub root node in my xml file like, <CapitalJobsList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <JobAds> -- element to create <JobAd> <AdvertiserDetails> <AdvertiserId>718508549</AdvertiserId> <AdvertiserName>ABC</AdvertiserName> </AdvertiserDetails> <ConsultantDetails> <ContactName>Naga Divakar</ContactName> <ContactPhone>6239 7755</ContactPhone> <ContactEmail>[email protected]</ContactEmail> <ContactFax>12345678912</ContactFax> </ConsultantDetails> <JobAdDetails> <DateEntered>2009-10-03T21:09:35.500</DateEntered> <AdvertiserJobRef>83754865</AdvertiserJobRef> <Title>IT Operations Manager</Title> <DescriptionShort>Large scale/exciting projects Mentor and manage o...</DescriptionShort> <Description>Large scale/exciting projects Mentor and manage others Management/technical mix This is a fantastic opportunity to join a high profile client who is active across both the commercial and Government domain. As the IT Operations Manager you will be responsible for leading and mentoring a small team of Infrastructure Engineers to ensure the availability and performance of the IT infrastructure. You w</Description> <SalaryMin>0.00</SalaryMin> <SalaryMax>0.00</SalaryMax> <WorkType xsi:nil="true" /> <Location>) as [JobAd/JobAdDetails/Bullets], isnull(Job</Location> <PostCode>2600</PostCode> <ClosingDate>2009-11-01T00:00:00</ClosingDate> <Keywords xsi:nil="true" /> <ApplyEmail xsi:nil="true" /> <ApplyURL>http://jobview.careerone.com.au/GetJob.aspx?JobID=83754865</ApplyURL> </JobAdDetails> <JobAdOptions> <BlindPost xsi:nil="true" /> <AdFormatType xsi:nil="true" /> <AdTemplateName xsi:nil="true" /> <ShowContactDetails xsi:nil="true" /> <ShowSalary xsi:nil="true" /> <HasVideo xsi:nil="true" /> <ResumeRequired>1</ResumeRequired> <ResidentsOnly>0</ResidentsOnly> </JobAdOptions> <CategoryList> <Category xsi:nil="true" /> </CategoryList> <RegionsList> <Region>ACT</Region> </RegionsList> <LevelsList> <Level xsi:nil="true" /> </LevelsList> </JobAd> <JobAd> <AdvertiserDetails> <AdvertiserId>718508549</AdvertiserId> <AdvertiserName>ABC</AdvertiserName> </AdvertiserDetails> <ConsultantDetails> <ContactName>Naga Divakar</ContactName> <ContactPhone>6239 7755</ContactPhone> <ContactEmail>[email protected]</ContactEmail> <ContactFax>12345678912</ContactFax> </ConsultantDetails> <JobAdDetails> <DateEntered>2009-10-03T21:09:35.530</DateEntered> <AdvertiserJobRef>83731488</AdvertiserJobRef> <Title>SAP Developers Required in Canberra - 12 month contract</Title> <DescriptionShort>My client, a large government department in Canbe...</DescriptionShort> <Description>My client, a large government department in Canberra, seeks two SAP Developers for 12 month ongoing contracts. Two SAP Developers Required Expert level ABAP programming skills Large SAP landscape - SAP R/3, SAP Web, SAP BI, SAP ITS My client, a large government department in Canberra, seeks two SAP Developers for 12 month ongoing contracts. My client is a large government department in Canberra, a</Description> <SalaryMin>0.00</SalaryMin> <SalaryMax>0.00</SalaryMax> <WorkType xsi:nil="true" /> <Location>) as [JobAd/JobAdDetails/Bullets], isnull(Job</Location> <PostCode>2600</PostCode> <ClosingDate>2009-11-01T00:00:00</ClosingDate> <Keywords xsi:nil="true" /> <ApplyEmail xsi:nil="true" /> <ApplyURL>http://jobview.careerone.com.au/GetJob.aspx?JobID=83731488</ApplyURL> </JobAdDetails> <JobAdOptions> <BlindPost xsi:nil="true" /> <AdFormatType xsi:nil="true" /> <AdTemplateName xsi:nil="true" /> <ShowContactDetails xsi:nil="true" /> <ShowSalary xsi:nil="true" /> <HasVideo xsi:nil="true" /> <ResumeRequired>1</ResumeRequired> <ResidentsOnly>0</ResidentsOnly> </JobAdOptions> <CategoryList> <Category xsi:nil="true" /> </CategoryList> <RegionsList> <Region>ACT</Region> </RegionsList> <LevelsList> <Level xsi:nil="true" /> </LevelsList> </JobAd> </JobAds> </CapitalJobsList> I have used the sql query for xml path like: select r.advid as [JobAd/AdvertiserDetails/AdvertiserId], CompanyName as [JobAd/AdvertiserDetails/AdvertiserName], firstname +'' ''+ lastname as [JobAd/ConsultantDetails/ContactName], WorkPhone as [JobAd/ConsultantDetails/ContactPhone], AdvEmail as [JobAd/ConsultantDetails/ContactEmail], FaxNo as [JobAd/ConsultantDetails/ContactFax], Job_CreatedDate as [JobAd/JobAdDetails/DateEntered], Job_Id as [JobAd/JobAdDetails/AdvertiserJobRef], Job_Title as [JobAd/JobAdDetails/Title], substring(Job_Description,0,50)+''...'' as [JobAd/JobAdDetails/DescriptionShort], Job_Description as [JobAd/JobAdDetails/Description], CONVERT(DECIMAL(10,2),MinSalary) as [JobAd/JobAdDetails/SalaryMin], CONVERT(DECIMAL(10,2),MaxSalary) as [JobAd/JobAdDetails/SalaryMax], Job_Type as [JobAd/JobAdDetails/WorkType], isnull(Job_Bullets,'') as [JobAd/JobAdDetails/Bullets], isnull(Job_Location,'') as [JobAd/JobAdDetails/Location], Job_PostCode as [JobAd/JobAdDetails/PostCode], Job_ExpireDate as [JobAd/JobAdDetails/ClosingDate], Job_Keywords as [JobAd/JobAdDetails/Keywords], ApplyEmail as [JobAd/JobAdDetails/ApplyEmail], Job_BrandURL+Job_Id as [JobAd/JobAdDetails/ApplyURL], BlindPost as [JobAd/JobAdOptions/BlindPost], AdFormatType as [JobAd/JobAdOptions/AdFormatType], AdTemplateName as [JobAd/JobAdOptions/AdTemplateName], ShowContactDetails as [JobAd/JobAdOptions/ShowContactDetails], ShowSalary as [JobAd/JobAdOptions/ShowSalary], HasVideo as [JobAd/JobAdOptions/HasVideo], ResumeRequired as [JobAd/JobAdOptions/ResumeRequired], ResidentsOnly as [JobAd/JobAdOptions/ResidentsOnly], Job_Category as [JobAd/CategoryList/Category], Job_Location_State as [JobAd/RegionsList/Region], [Level] as [JobAd/LevelsList/Level] from DR_Adv_Registration r, DR_CareerOne_ACTJobs j where r.Advid = j.Advid and job_location_city like(''%'+''+ @City +''+'%'') and job_location_state in('''+ @State +''') and job_status=1 for xml path(''''), Root(''CapitalJobsList''),ELEMENTS XSINIL So, suggest me how to get the sub root node. Thanks in advance

    Read the article

  • filtering jqgrid based on user input

    - by Rohan
    hi, everything is working fine with my jqgrid except a small issue. i have defined postData below: $(document).ready(function() { $("#ctl00_ContentPlaceHolder2_drpUSite").change(function() { site = ($("#ctl00_ContentPlaceHolder2_drpUSite").val()); loadusergrid(); }); var usrparams = new Object(); var site = ($("#ctl00_ContentPlaceHolder2_drpUSite").val()); //----grid code--------- $("#users").jqGrid({ prmNames: { _search: "isSearch", nd: null, rows: "numRows", page: "page", sort: "sortField", order: "sortOrder" }, // add by default to avoid webmethod parameter conflicts postData: { searchString: '', searchField: '', searchOper: '', sites: site }, datatype: function(postdata) { mtype: "GET", $.ajax({ url: 'Users.aspx/GetUsers', type: "POST", contentType: "application/json; charset=utf-8", data: JSON.stringify(postdata), dataType: "json", success: function(data, st) { if (st == "success") { var grid = $("#users")[0]; var m = JSON.parse(data.d); grid.addJSONData(m); } }, error: function() { alert("Loading Failed!"); } }); }, // this is what jqGrid is looking for in json callback jsonReader: { root: "rows", page: "page", total: "total", records: "records", cell: "cell", id: "login", repeatitems: true }, colNames: ['Login', 'First Name', 'Last Name', 'Email', 'Site', 'Role', 'Room', 'UnitID', 'Supervisor', 'Super'], colModel: [ { name: 'login', index: 'login', width: 20 }, { name: 'fname', index: 'fname', width: 20, hidden: true }, { name: 'lname', index: 'lname', width: 60, align: "center", sortable: true, searchoptions: { sopt: ['eq', 'ne']} }, { name: 'email', index: 'email', width: 20, align: "center", sortable: false }, { name: 'site', index: 'site', width: 50, align: "center", sortable: true, searchoptions: { sopt: ['eq', 'ne']} }, { name: 'role', index: 'role', width: 15, align: "center", sortable: true, searchoptions: { sopt: ['eq', 'ne']} }, { name: 'room', index: 'room', width: 30, align: "center", sortable: true }, { name: 'unitid', index: 'unitid', width: 10, align: "center", sortable: false }, { name: 'super', index: 'super', width: 20 }, { name: 'supername', index: 'supername', width: 10, align: "center", sortable: false }, ], pager: "#pageusers", viewrecords: true, caption: "Registered Users", imgpath: 'themes/steel/images', rowNum: 20, rowList: [10, 20, 30, 40, 50], sortname: "pname", sortorder: "desc", showpage: true, gridModel: true, gridToolbar: true, onSelectRow: function(id) { var ret = jQuery("#users").getRowData(id); accpara.id = ret.id; accpara.pname = ret.pname; accpara.pid = ret.pid; accpara.bld = ret.bld; accpara.cname = ret.cname; accpara.amt = ret.amt; accpara.status = ret.status; accpara.notes = ret.notes; accpara.lname = ret.lname; } }); jQuery("#users").navGrid('#pageusers', { view: false, del: false, add: false, edit: false }, {}, // default settings for edit {}, // default settings for add {}, // delete {closeOnEscape: true, multipleSearch: true, closeAfterSearch: true }, // search options {} ); $("#users").setGridWidth(1300, true); $("#users").setGridHeight(500, true); jQuery("#users").jqGrid('filterToolbar'); //----grid code ends here function loadusergrid() { $("#users").setGridParam({ page: 1 }, { pgbuttons: true }, { pginput: true }, { postData: { "site": site} }).trigger("reloadGrid"); } }); when page loads for the 1st time, this works.. now i have 4 drop-downs which filter users. i have written a function which reloads the grid when the dropdown is changed, but it isnt working.. what am i doing wrong here?? when i enable postback for the dropdowns, i get the filtered result. i want to avoid postbacks on my page :). right now i have added just the site dropdown as the filter. once this starts working ill add the remaining 3. firebug shows the ajax call is fired successfully but with an empty sitename. please note that the site dropdown cntains an empty value when page is loaded for the 1st time. thanks in advance

    Read the article

  • jqgrid retrieving empty rows using webapi (REST)

    - by polonskyg
    I'm using jqgrid in an ASPNET MVC4 project with WebApi (REST), Entity Framework 5 using Unit Of Work and Repository patterns. My problem is that I see the data flowing as json to the browser and I see three rows in the grid, but those rows are empty, and the data is not shown (three empty rows in the grid). This is method to get the data in the WebApi controller: public dynamic GetGridData(int rows, int page, string sidx, string sord) { var pageSize = rows; var index = sidx; var order = sord; var categories = Uow.Categories.GetAll().OrderBy(t => (string.IsNullOrEmpty(index) ? "Id" : index) + " " + (order ?? "desc")); var pageIndex = Convert.ToInt32(page) - 1; var totalRecords = categories.Count(); var totalPages = (int)Math.Ceiling((float) totalRecords / (float) pageSize); var categoriesPage = categories.Skip(pageIndex * pageSize).Take(pageSize).ToList(); return new { total = totalPages, page = page, records = totalRecords, rows = (from category in categoriesPage select new { id = category.Id.ToString(), cell = new string[] { category.Id.ToString(), category.Name, category.Description } }).ToArray() }; } This is the json received in the browser { "total": 1, "page": 1, "records": 3, "rows": [{ "id": "1", "cell": ["1", "Category 1", null] }, { "id": "3", "cell": ["3", "Category 3", "asAS"] }, { "id": "4", "cell": ["4", "Category 4", null] }] } This is the .js file with jqgrid jQuery("#ajaxGrid").jqGrid({ url: $("#ServiceUrl").val(), datatype: "json", jsonReader: { repeatitems: false, id: "Id" }, colNames: ['Id', 'Name', 'Description'], colModel: [ { name: 'id', editable: true, sortable: true, hidden: true, align: 'left' }, { name: 'name', editable: true, sortable: true, hidden: false, align: 'left' }, { name: 'description', editable: true, sortable: true, hidden: false, align: 'left' } ], mtype: 'GET', rowNum: 15, pager: '#ajaxGridPager', rowList: [10, 20, 50, 100], caption: 'List of Categories', imgpath: $("#ServiceImagesUrl").val(), altRows: true, shrinkToFit: true, viewrecords: true, autowidth: true, height: 'auto', error: function(x, e) { alert(x.readyState + " "+ x.status +" "+ e.msg); } }); function updateDialog(action) { return { url: $("#ServiceUrl").val(), closeAfterAdd: true, closeAfterEdit: true, afterShowForm: function (formId) { }, modal: true, onclickSubmit: function (params) { var list = $("#ajaxGrid"); var selectedRow = list.getGridParam("selrow"); params.url += "/" + list.getRowData(selectedRow).Id; params.mtype = action; }, width: "300", ajaxEditOptions: { contentType: "application/json" }, serializeEditData: function (data) { delete data.oper; return JSON.stringify(data); } }; } jQuery("#ajaxGrid").jqGrid( 'navGrid', '#ajaxGridPager', { add: true, edit: true, del: true, search: false, refresh: false }, updateDialog('PUT'), updateDialog('POST'), updateDialog('DELETE') ); BTW, If I want to return jqGridData instead the dynamic, How should I do it? Did is showing empty rows as well: public class jqGridData<T> where T : class { public int page { get; set; } public int records { get; set; } public IEnumerable<T> rows { get; set; } public decimal total { get; set; } } public jqGridData<Category> GetGridData(int rows, int page, string sidx, string sord) { var pageSize = rows; var index = sidx; var order = sord; var categories = Uow.Categories.GetAll().OrderBy(t => (string.IsNullOrEmpty(index) ? "Id" : index) + " " + (order ?? "desc")); var pageIndex = Convert.ToInt32(page) - 1; var totalRecords = categories.Count(); var totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize); var categoriesPage = categories.Skip(pageIndex * pageSize).Take(pageSize); return new jqGridData<Category> { page = page, records = totalRecords, total = totalPages, rows = categoriesPage }; }

    Read the article

  • The maven assembly plugin is not using the finalName for installing with attach=true?

    - by Roland Wiesemann
    I have configured following assembly: <build> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>2.2-beta-5</version> <executions> <execution> <id>${project.name}-test-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <appendAssemblyId>false</appendAssemblyId> <finalName>${project.name}-test</finalName> <filters> <filter>src/assemble/test/distribution.properties</filter> </filters> <descriptors> <descriptor>src/assemble/distribution.xml</descriptor> </descriptors> <attach>true</attach> </configuration> </execution> <execution> <id>${project.name}-prod-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <appendAssemblyId>false</appendAssemblyId> <finalName>${project.name}-prod</finalName> <filters> <filter>src/assemble/prod/distribution.properties</filter> </filters> <descriptors> <descriptor>src/assemble/distribution.xml</descriptor> </descriptors> <attach>true</attach> </configuration> </execution> </executions> </plugin> </plugins> </build> This produced two zip-files: distribution-prod.zip distribution-test.zip My expectation for the property attach=true is, that the two zip-files are installed with the name as given in property finalName. But the result is, only one file is installed (attached) to the artifact. The maven protocol is: distrib-0.1-SNAPSHOT.zip distrib-0.1-SNAPSHOT.zip The plugin is using the artifact-id instead of property finalName! Is this a bug? The last installation is overwriting the first one. What can i do to install this two files with different names? Thanks for your investigation. Roland

    Read the article

  • Using VBA / Macro to highlight changes in excel

    - by Zaj
    I have a spread sheet that I send out to various locations to have information on it updated and then sent back to me. However, I had to put validation and lock the cells to force users to input accurate information. Then I can to use VBA to disable the work around of cut copy and paste functions. And additionally I inserted a VBA function to force users to open the excel file in Macros. Now I'm trying to track the changes so that I know what was updated when I recieve the sheet back. However everytime i do this I get an error when someone savesthe document and randomly it will lock me out of the document completely. I have my code pasted below, can some one help me create code in the VBA forum to highlight changes instead of through excel's share/track changes option? ThisWorkbook (Code): Option Explicit Const WelcomePage = "Macros" Private Sub Workbook_BeforeClose(Cancel As Boolean) Call ToggleCutCopyAndPaste(True) 'Turn off events to prevent unwanted loops Application.EnableEvents = False 'Evaluate if workbook is saved and emulate default propmts With ThisWorkbook If Not .Saved Then Select Case MsgBox("Do you want to save the changes you made to '" & .Name & "'?", _ vbYesNoCancel + vbExclamation) Case Is = vbYes 'Call customized save routine Call CustomSave Case Is = vbNo 'Do not save Case Is = vbCancel 'Set up procedure to cancel close Cancel = True End Select End If 'If Cancel was clicked, turn events back on and cancel close, 'otherwise close the workbook without saving further changes If Not Cancel = True Then .Saved = True Application.EnableEvents = True .Close savechanges:=False Else Application.EnableEvents = True End If End With End Sub Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) 'Turn off events to prevent unwanted loops Application.EnableEvents = False 'Call customized save routine and set workbook's saved property to true '(To cancel regular saving) Call CustomSave(SaveAsUI) Cancel = True 'Turn events back on an set saved property to true Application.EnableEvents = True ThisWorkbook.Saved = True End Sub Private Sub Workbook_Open() Call ToggleCutCopyAndPaste(False) 'Unhide all worksheets Application.ScreenUpdating = False Call ShowAllSheets Application.ScreenUpdating = True End Sub Private Sub CustomSave(Optional SaveAs As Boolean) Dim ws As Worksheet, aWs As Worksheet, newFname As String 'Turn off screen flashing Application.ScreenUpdating = False 'Record active worksheet Set aWs = ActiveSheet 'Hide all sheets Call HideAllSheets 'Save workbook directly or prompt for saveas filename If SaveAs = True Then newFname = Application.GetSaveAsFilename( _ fileFilter:="Excel Files (*.xls), *.xls") If Not newFname = "False" Then ThisWorkbook.SaveAs newFname Else ThisWorkbook.Save End If 'Restore file to where user was Call ShowAllSheets aWs.Activate 'Restore screen updates Application.ScreenUpdating = True End Sub Private Sub HideAllSheets() 'Hide all worksheets except the macro welcome page Dim ws As Worksheet Worksheets(WelcomePage).Visible = xlSheetVisible For Each ws In ThisWorkbook.Worksheets If Not ws.Name = WelcomePage Then ws.Visible = xlSheetVeryHidden Next ws Worksheets(WelcomePage).Activate End Sub Private Sub ShowAllSheets() 'Show all worksheets except the macro welcome page Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets If Not ws.Name = WelcomePage Then ws.Visible = xlSheetVisible Next ws Worksheets(WelcomePage).Visible = xlSheetVeryHidden End Sub Private Sub Workbook_Activate() Call ToggleCutCopyAndPaste(False) End Sub Private Sub Workbook_Deactivate() Call ToggleCutCopyAndPaste(True) End Sub This is in my ModuleCode: Option Explicit Sub ToggleCutCopyAndPaste(Allow As Boolean) 'Activate/deactivate cut, copy, paste and pastespecial menu items Call EnableMenuItem(21, Allow) ' cut Call EnableMenuItem(19, Allow) ' copy Call EnableMenuItem(22, Allow) ' paste Call EnableMenuItem(755, Allow) ' pastespecial 'Activate/deactivate drag and drop ability Application.CellDragAndDrop = Allow 'Activate/deactivate cut, copy, paste and pastespecial shortcut keys With Application Select Case Allow Case Is = False .OnKey "^c", "CutCopyPasteDisabled" .OnKey "^v", "CutCopyPasteDisabled" .OnKey "^x", "CutCopyPasteDisabled" .OnKey "+{DEL}", "CutCopyPasteDisabled" .OnKey "^{INSERT}", "CutCopyPasteDisabled" Case Is = True .OnKey "^c" .OnKey "^v" .OnKey "^x" .OnKey "+{DEL}" .OnKey "^{INSERT}" End Select End With End Sub Sub EnableMenuItem(ctlId As Integer, Enabled As Boolean) 'Activate/Deactivate specific menu item Dim cBar As CommandBar Dim cBarCtrl As CommandBarControl For Each cBar In Application.CommandBars If cBar.Name <> "Clipboard" Then Set cBarCtrl = cBar.FindControl(ID:=ctlId, recursive:=True) If Not cBarCtrl Is Nothing Then cBarCtrl.Enabled = Enabled End If Next End Sub Sub CutCopyPasteDisabled() 'Inform user that the functions have been disabled MsgBox " Cutting, copying and pasting have been disabled in this workbook. Please hard key in data. " End Sub

    Read the article

  • ASP.NET Podcast Show #148 - ASP.NET WebForms to build a Mobile Web Application

    - by Wallym
    Check the podcast site for the original url. This is the video and source code for an ASP.NET WebForms app that I wrote that is optimized for the iPhone and mobile environments.  Subscribe to everything. Subscribe to WMV. Subscribe to M4V for iPhone/iPad. Subscribe to MP3. Download WMV. Download M4V for iPhone/iPad. Download MP3. Link to iWebKit. Source Code: <%@ Page Title="MapSplore" Language="C#" MasterPageFile="iPhoneMaster.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="AT_iPhone_Default" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"></asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="Content" Runat="Server" ClientIDMode="Static">    <asp:ScriptManager ID="sm" runat="server"         EnablePartialRendering="true" EnableHistory="false" EnableCdn="true" />    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>    <script  language="javascript"  type="text/javascript">    <!--    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandle);    function endRequestHandle(sender, Args) {        setupMapDiv();        setupPlaceIveBeen();    }    function setupPlaceIveBeen() {        var mapPlaceIveBeen = document.getElementById('divPlaceIveBeen');        if (mapPlaceIveBeen != null) {            var PlaceLat = document.getElementById('<%=hdPlaceIveBeenLatitude.ClientID %>').value;            var PlaceLon = document.getElementById('<%=hdPlaceIveBeenLongitude.ClientID %>').value;            var PlaceTitle = document.getElementById('<%=lblPlaceIveBeenName.ClientID %>').innerHTML;            var latlng = new google.maps.LatLng(PlaceLat, PlaceLon);            var myOptions = {                zoom: 14,                center: latlng,                mapTypeId: google.maps.MapTypeId.ROADMAP            };            var map = new google.maps.Map(mapPlaceIveBeen, myOptions);            var marker = new google.maps.Marker({                position: new google.maps.LatLng(PlaceLat, PlaceLon),                map: map,                title: PlaceTitle,                clickable: false            });        }    }    function setupMapDiv() {        var mapdiv = document.getElementById('divImHere');        if (mapdiv != null) {            var PlaceLat = document.getElementById('<%=hdPlaceLat.ClientID %>').value;            var PlaceLon = document.getElementById('<%=hdPlaceLon.ClientID %>').value;            var PlaceTitle = document.getElementById('<%=hdPlaceTitle.ClientID %>').value;            var latlng = new google.maps.LatLng(PlaceLat, PlaceLon);            var myOptions = {                zoom: 14,                center: latlng,                mapTypeId: google.maps.MapTypeId.ROADMAP            };            var map = new google.maps.Map(mapdiv, myOptions);            var marker = new google.maps.Marker({                position: new google.maps.LatLng(PlaceLat, PlaceLon),                map: map,                title: PlaceTitle,                clickable: false            });        }     }    -->    </script>    <asp:HiddenField ID="Latitude" runat="server" />    <asp:HiddenField ID="Longitude" runat="server" />    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js%22%3E%3C/script>    <script language="javascript" type="text/javascript">        $(document).ready(function () {            GetLocation();            setupMapDiv();            setupPlaceIveBeen();        });        function GetLocation() {            if (navigator.geolocation != null) {                navigator.geolocation.getCurrentPosition(getData);            }            else {                var mess = document.getElementById('<%=Message.ClientID %>');                mess.innerHTML = "Sorry, your browser does not support geolocation. " +                    "Try the latest version of Safari on the iPhone, Android browser, or the latest version of FireFox.";            }        }        function UpdateLocation_Click() {            GetLocation();        }        function getData(position) {            var latitude = position.coords.latitude;            var longitude = position.coords.longitude;            var hdLat = document.getElementById('<%=Latitude.ClientID %>');            var hdLon = document.getElementById('<%=Longitude.ClientID %>');            hdLat.value = latitude;            hdLon.value = longitude;        }    </script>    <asp:Label ID="Message" runat="server" />    <asp:UpdatePanel ID="upl" runat="server">        <ContentTemplate>    <asp:Panel ID="pnlStart" runat="server" Visible="true">    <div id="topbar">        <div id="title">MapSplore</div>    </div>    <div id="content">        <ul class="pageitem">            <li class="menu">                <asp:LinkButton ID="lbLocalDeals" runat="server" onclick="lbLocalDeals_Click">                <asp:Image ID="imLocalDeals" runat="server" ImageUrl="~/Images/ArtFavor_Money_Bag_Icon.png" Height="30" />                <span class="name">Local Deals.</span>                <span class="arrow"></span>                </asp:LinkButton>                </li>            <li class="menu">                <asp:LinkButton ID="lbLocalPlaces" runat="server" onclick="lbLocalPlaces_Click">                <asp:Image ID="imLocalPlaces" runat="server" ImageUrl="~/Images/Andy_Houses_on_the_horizon_-_Starburst_remix.png" Height="30" />                <span class="name">Local Places.</span>                <span class="arrow"></span>                </asp:LinkButton>                </li>            <li class="menu">                <asp:LinkButton ID="lbWhereIveBeen" runat="server" onclick="lbWhereIveBeen_Click">                <asp:Image ID="imImHere" runat="server" ImageUrl="~/Images/ryanlerch_flagpole.png" Height="30" />                <span class="name">I've been here.</span>                <span class="arrow"></span>                </asp:LinkButton>                </li>            <li class="menu">                <asp:LinkButton ID="lbMyStats" runat="server">                <asp:Image ID="imMyStats" runat="server" ImageUrl="~/Images/Anonymous_Spreadsheet.png" Height="30" />                <span class="name">My Stats.</span>                <span class="arrow"></span>                </asp:LinkButton>                </li>            <li class="menu">                <asp:LinkButton ID="lbAddAPlace" runat="server" onclick="lbAddAPlace_Click">                <asp:Image ID="imAddAPlace" runat="server" ImageUrl="~/Images/jean_victor_balin_add.png" Height="30" />                <span class="name">Add a Place.</span>                <span class="arrow"></span>                </asp:LinkButton>                </li>            <li class="button">                <input type="button" value="Update Your Current Location" onclick="UpdateLocation_Click()">                </li>        </ul>    </div>    </asp:Panel>    <div>    <asp:Panel ID="pnlCoupons" runat="server" Visible="false">        <div id="topbar">        <div id="title">MapSplore</div>        <div id="leftbutton">            <asp:LinkButton runat="server" Text="Return"                 ID="ReturnFromDeals" OnClick="ReturnFromDeals_Click" /></div></div>    <div class="content">    <asp:ListView ID="lvCoupons" runat="server">        <LayoutTemplate>            <ul class="pageitem" runat="server">                <asp:PlaceHolder ID="itemPlaceholder" runat="server" />            </ul>        </LayoutTemplate>        <ItemTemplate>            <li class="menu">                <asp:LinkButton ID="lbBusiness" runat="server" Text='<%#Eval("Place.Name") %>' OnClick="lbBusiness_Click">                    <span class="comment">                    <asp:Label ID="lblAddress" runat="server" Text='<%#Eval("Place.Address1") %>' />                    <asp:Label ID="lblDis" runat="server" Text='<%# Convert.ToString(Convert.ToInt32(Eval("Place.Distance"))) + " meters" %>' CssClass="smallText" />                    <asp:HiddenField ID="hdPlaceId" runat="server" Value='<%#Eval("PlaceId") %>' />                    <asp:HiddenField ID="hdGeoPromotionId" runat="server" Value='<%#Eval("GeoPromotionId") %>' />                    </span>                    <span class="arrow"></span>                </asp:LinkButton></li></ItemTemplate></asp:ListView><asp:GridView ID="gvCoupons" runat="server" AutoGenerateColumns="false">            <HeaderStyle BackColor="Silver" />            <AlternatingRowStyle BackColor="Wheat" />            <Columns>                <asp:TemplateField AccessibleHeaderText="Business" HeaderText="Business">                    <ItemTemplate>                        <asp:Image ID="imPlaceType" runat="server" Text='<%#Eval("Type") %>' ImageUrl='<%#Eval("Image") %>' />                        <asp:LinkButton ID="lbBusiness" runat="server" Text='<%#Eval("Name") %>' OnClick="lbBusiness_Click" />                        <asp:LinkButton ID="lblAddress" runat="server" Text='<%#Eval("Address1") %>' CssClass="smallText" />                        <asp:Label ID="lblDis" runat="server" Text='<%# Convert.ToString(Convert.ToInt32(Eval("Distance"))) + " meters" %>' CssClass="smallText" />                        <asp:HiddenField ID="hdPlaceId" runat="server" Value='<%#Eval("PlaceId") %>' />                        <asp:HiddenField ID="hdGeoPromotionId" runat="server" Value='<%#Eval("GeoPromotionId") %>' />                        <asp:Label ID="lblInfo" runat="server" Visible="false" />                    </ItemTemplate>                </asp:TemplateField>            </Columns>        </asp:GridView>    </div>    </asp:Panel>    <asp:Panel ID="pnlPlaces" runat="server" Visible="false">    <div id="topbar">        <div id="title">            MapSplore</div><div id="leftbutton">            <asp:LinkButton runat="server" Text="Return"                 ID="ReturnFromPlaces" OnClick="ReturnFromPlaces_Click" /></div></div>        <div id="content">        <asp:ListView ID="lvPlaces" runat="server">            <LayoutTemplate>                <ul id="ulPlaces" class="pageitem" runat="server">                    <asp:PlaceHolder ID="itemPlaceholder" runat="server" />                    <li class="menu">                        <asp:LinkButton ID="lbNotListed" runat="server" CssClass="name"                            OnClick="lbNotListed_Click">                            Place not listed                            <span class="arrow"></span>                            </asp:LinkButton>                    </li>                </ul>            </LayoutTemplate>            <ItemTemplate>            <li class="menu">                <asp:LinkButton ID="lbImHere" runat="server" CssClass="name"                     OnClick="lbImHere_Click">                <%#DisplayName(Eval("Name")) %>&nbsp;                <%# Convert.ToString(Convert.ToInt32(Eval("Distance"))) + " meters" %>                <asp:HiddenField ID="hdPlaceId" runat="server" Value='<%#Eval("PlaceId") %>' />                <span class="arrow"></span>                </asp:LinkButton></li></ItemTemplate></asp:ListView>    </div>    </asp:Panel>    <asp:Panel ID="pnlImHereNow" runat="server" Visible="false">        <div id="topbar">        <div id="title">            MapSplore</div><div id="leftbutton">            <asp:LinkButton runat="server" Text="Places"                 ID="lbImHereNowReturn" OnClick="lbImHereNowReturn_Click" /></div></div>            <div id="rightbutton">            <asp:LinkButton runat="server" Text="Beginning"                ID="lbBackToBeginning" OnClick="lbBackToBeginning_Click" />            </div>        <div id="content">        <ul class="pageitem">        <asp:HiddenField ID="hdPlaceId" runat="server" />        <asp:HiddenField ID="hdPlaceLat" runat="server" />        <asp:HiddenField ID="hdPlaceLon" runat="server" />        <asp:HiddenField ID="hdPlaceTitle" runat="server" />        <asp:Button ID="btnImHereNow" runat="server"             Text="I'm here" OnClick="btnImHereNow_Click" />             <asp:Label ID="lblPlaceTitle" runat="server" /><br />        <asp:TextBox ID="txtWhatsHappening" runat="server" TextMode="MultiLine" Rows="2" style="width:300px" /><br />        <div id="divImHere" style="width:300px; height:300px"></div>        </div>        </ul>    </asp:Panel>    <asp:Panel runat="server" ID="pnlIveBeenHere" Visible="false">        <div id="topbar">        <div id="title">            Where I've been</div><div id="leftbutton">            <asp:LinkButton ID="lbIveBeenHereBack" runat="server" Text="Back" OnClick="lbIveBeenHereBack_Click" /></div></div>        <div id="content">        <asp:ListView ID="lvWhereIveBeen" runat="server">            <LayoutTemplate>                <ul id="ulWhereIveBeen" class="pageitem" runat="server">                    <asp:PlaceHolder ID="itemPlaceholder" runat="server" />                </ul>            </LayoutTemplate>            <ItemTemplate>            <li class="menu" runat="server">                <asp:LinkButton ID="lbPlaceIveBeen" runat="server" OnClick="lbPlaceIveBeen_Click" CssClass="name">                    <asp:Label ID="lblPlace" runat="server" Text='<%#Eval("PlaceName") %>' /> at                    <asp:Label ID="lblTime" runat="server" Text='<%#Eval("ATTime") %>' CssClass="content" />                    <asp:HiddenField ID="hdATID" runat="server" Value='<%#Eval("ATID") %>' />                    <span class="arrow"></span>                </asp:LinkButton>            </li>            </ItemTemplate>        </asp:ListView>        </div>        </asp:Panel>    <asp:Panel runat="server" ID="pnlPlaceIveBeen" Visible="false">        <div id="topbar">        <div id="title">            I've been here        </div>        <div id="leftbutton">            <asp:LinkButton ID="lbPlaceIveBeenBack" runat="server" Text="Back" OnClick="lbPlaceIveBeenBack_Click" />        </div>        <div id="rightbutton">            <asp:LinkButton ID="lbPlaceIveBeenBeginning" runat="server" Text="Beginning" OnClick="lbPlaceIveBeenBeginning_Click" />        </div>        </div>        <div id="content">            <ul class="pageitem">            <li>            <asp:HiddenField ID="hdPlaceIveBeenPlaceId" runat="server" />            <asp:HiddenField ID="hdPlaceIveBeenLatitude" runat="server" />            <asp:HiddenField ID="hdPlaceIveBeenLongitude" runat="server" />            <asp:Label ID="lblPlaceIveBeenName" runat="server" /><br />            <asp:Label ID="lblPlaceIveBeenAddress" runat="server" /><br />            <asp:Label ID="lblPlaceIveBeenCity" runat="server" />,             <asp:Label ID="lblPlaceIveBeenState" runat="server" />            <asp:Label ID="lblPlaceIveBeenZipCode" runat="server" /><br />            <asp:Label ID="lblPlaceIveBeenCountry" runat="server" /><br />            <div id="divPlaceIveBeen" style="width:300px; height:300px"></div>            </li>            </ul>        </div>                </asp:Panel>         <asp:Panel ID="pnlAddPlace" runat="server" Visible="false">                <div id="topbar"><div id="title">MapSplore</div><div id="leftbutton"><asp:LinkButton ID="lbAddPlaceReturn" runat="server" Text="Back" OnClick="lbAddPlaceReturn_Click" /></div><div id="rightnav"></div></div><div id="content">    <ul class="pageitem">        <li id="liPlaceAddMessage" runat="server" visible="false">        <asp:Label ID="PlaceAddMessage" runat="server" />        </li>        <li class="bigfield">        <asp:TextBox ID="txtPlaceName" runat="server" placeholder="Name of Establishment" />        </li>        <li class="bigfield">        <asp:TextBox ID="txtAddress1" runat="server" placeholder="Address 1" />        </li>        <li class="bigfield">        <asp:TextBox ID="txtCity" runat="server" placeholder="City" />        </li>        <li class="select">        <asp:DropDownList ID="ddlProvince" runat="server" placeholder="Select State" />          <span class="arrow"></span>              </li>        <li class="bigfield">        <asp:TextBox ID="txtZipCode" runat="server" placeholder="Zip Code" />        </li>        <li class="select">        <asp:DropDownList ID="ddlCountry" runat="server"             onselectedindexchanged="ddlCountry_SelectedIndexChanged" />        <span class="arrow"></span>        </li>        <li class="bigfield">        <asp:TextBox ID="txtPhoneNumber" runat="server" placeholder="Phone Number" />        </li>        <li class="checkbox">            <span class="name">You Here Now:</span> <asp:CheckBox ID="cbYouHereNow" runat="server" Checked="true" />        </li>        <li class="button">        <asp:Button ID="btnAdd" runat="server" Text="Add Place"             onclick="btnAdd_Click" />        </li>    </ul></div>        </asp:Panel>        <asp:Panel ID="pnlImHere" runat="server" Visible="false">            <asp:TextBox ID="txtImHere" runat="server"                 TextMode="MultiLine" Rows="3" Columns="40" /><br />            <asp:DropDownList ID="ddlPlace" runat="server" /><br />            <asp:Button ID="btnHere" runat="server" Text="Tell Everyone I'm Here"                 onclick="btnHere_Click" /><br />        </asp:Panel>     </div>    </ContentTemplate>    </asp:UpdatePanel> </asp:Content> Code Behind .cs file: using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using LocationDataModel; public partial class AT_iPhone_Default : ViewStatePage{    private iPhoneDevice ipd;     protected void Page_Load(object sender, EventArgs e)    {        LocationDataEntities lde = new LocationDataEntities();        if (!Page.IsPostBack)        {            var Countries = from c in lde.Countries select c;            foreach (Country co in Countries)            {                ddlCountry.Items.Add(new ListItem(co.Name, co.CountryId.ToString()));            }            ddlCountry_SelectedIndexChanged(ddlCountry, null);            if (AppleIPhone.IsIPad())                ipd = iPhoneDevice.iPad;            if (AppleIPhone.IsIPhone())                ipd = iPhoneDevice.iPhone;            if (AppleIPhone.IsIPodTouch())                ipd = iPhoneDevice.iPodTouch;        }    }    protected void btnPlaces_Click(object sender, EventArgs e)    {    }    protected void btnAdd_Click(object sender, EventArgs e)    {        bool blImHere = cbYouHereNow.Checked;        string Place = txtPlaceName.Text,            Address1 = txtAddress1.Text,            City = txtCity.Text,            ZipCode = txtZipCode.Text,            PhoneNumber = txtPhoneNumber.Text,            ProvinceId = ddlProvince.SelectedItem.Value,            CountryId = ddlCountry.SelectedItem.Value;        int iProvinceId, iCountryId;        double dLatitude, dLongitude;        DataAccess da = new DataAccess();        if ((!String.IsNullOrEmpty(ProvinceId)) &&            (!String.IsNullOrEmpty(CountryId)))        {            iProvinceId = Convert.ToInt32(ProvinceId);            iCountryId = Convert.ToInt32(CountryId);            if (blImHere)            {                dLatitude = Convert.ToDouble(Latitude.Value);                dLongitude = Convert.ToDouble(Longitude.Value);                da.StorePlace(Place, Address1, String.Empty, City,                    iProvinceId, ZipCode, iCountryId, PhoneNumber,                    dLatitude, dLongitude);            }            else            {                da.StorePlace(Place, Address1, String.Empty, City,                    iProvinceId, ZipCode, iCountryId, PhoneNumber);            }            liPlaceAddMessage.Visible = true;            PlaceAddMessage.Text = "Awesome, your place has been added. Add Another!";            txtPlaceName.Text = String.Empty;            txtAddress1.Text = String.Empty;            txtCity.Text = String.Empty;            ddlProvince.SelectedIndex = -1;            txtZipCode.Text = String.Empty;            txtPhoneNumber.Text = String.Empty;        }        else        {            liPlaceAddMessage.Visible = true;            PlaceAddMessage.Text = "Please select a State and a Country.";        }    }    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)    {        string CountryId = ddlCountry.SelectedItem.Value;        if (!String.IsNullOrEmpty(CountryId))        {            int iCountryId = Convert.ToInt32(CountryId);            LocationDataModel.LocationDataEntities lde = new LocationDataModel.LocationDataEntities();            var prov = from p in lde.Provinces where p.CountryId == iCountryId                        orderby p.ProvinceName select p;                        ddlProvince.Items.Add(String.Empty);            foreach (Province pr in prov)            {                ddlProvince.Items.Add(new ListItem(pr.ProvinceName, pr.ProvinceId.ToString()));            }        }        else        {            ddlProvince.Items.Clear();        }    }    protected void btnImHere_Click(object sender, EventArgs e)    {        int i = 0;        DataAccess da = new DataAccess();        double Lat = Convert.ToDouble(Latitude.Value),            Lon = Convert.ToDouble(Longitude.Value);        List<Place> lp = da.NearByLocations(Lat, Lon);        foreach (Place p in lp)        {            ListItem li = new ListItem(p.Name, p.PlaceId.ToString());            if (i == 0)            {                li.Selected = true;            }            ddlPlace.Items.Add(li);            i++;        }        pnlAddPlace.Visible = false;        pnlImHere.Visible = true;    }    protected void lbImHere_Click(object sender, EventArgs e)    {        string UserName = Membership.GetUser().UserName;        ListViewItem lvi = (ListViewItem)(((LinkButton)sender).Parent);        HiddenField hd = (HiddenField)lvi.FindControl("hdPlaceId");        long PlaceId = Convert.ToInt64(hd.Value);        double dLatitude = Convert.ToDouble(Latitude.Value);        double dLongitude = Convert.ToDouble(Longitude.Value);        DataAccess da = new DataAccess();        Place pl = da.GetPlace(PlaceId);        pnlImHereNow.Visible = true;        pnlPlaces.Visible = false;        hdPlaceId.Value = PlaceId.ToString();        hdPlaceLat.Value = pl.Latitude.ToString();        hdPlaceLon.Value = pl.Longitude.ToString();        hdPlaceTitle.Value = pl.Name;        lblPlaceTitle.Text = pl.Name;    }    protected void btnHere_Click(object sender, EventArgs e)    {        string UserName = Membership.GetUser().UserName;        string WhatsH = txtImHere.Text;        long PlaceId = Convert.ToInt64(ddlPlace.SelectedValue);        double dLatitude = Convert.ToDouble(Latitude.Value);        double dLongitude = Convert.ToDouble(Longitude.Value);        DataAccess da = new DataAccess();        da.StoreUserAT(UserName, PlaceId, WhatsH,            dLatitude, dLongitude);    }    protected void btnLocalCoupons_Click(object sender, EventArgs e)    {        double dLatitude = Convert.ToDouble(Latitude.Value);        double dLongitude = Convert.ToDouble(Longitude.Value);        DataAccess da = new DataAccess();     }    protected void lbBusiness_Click(object sender, EventArgs e)    {        string UserName = Membership.GetUser().UserName;        GridViewRow gvr = (GridViewRow)(((LinkButton)sender).Parent.Parent);        HiddenField hd = (HiddenField)gvr.FindControl("hdPlaceId");        string sPlaceId = hd.Value;        Int64 PlaceId;        if (!String.IsNullOrEmpty(sPlaceId))        {            PlaceId = Convert.ToInt64(sPlaceId);        }    }    protected void lbLocalDeals_Click(object sender, EventArgs e)    {        double dLatitude = Convert.ToDouble(Latitude.Value);        double dLongitude = Convert.ToDouble(Longitude.Value);        DataAccess da = new DataAccess();        pnlCoupons.Visible = true;        pnlStart.Visible = false;        List<GeoPromotion> lgp = da.NearByDeals(dLatitude, dLongitude);        lvCoupons.DataSource = lgp;        lvCoupons.DataBind();    }    protected void lbLocalPlaces_Click(object sender, EventArgs e)    {        DataAccess da = new DataAccess();        double Lat = Convert.ToDouble(Latitude.Value);        double Lon = Convert.ToDouble(Longitude.Value);        List<LocationDataModel.Place> places = da.NearByLocations(Lat, Lon);        lvPlaces.DataSource = places;        lvPlaces.SelectedIndex = -1;        lvPlaces.DataBind();        pnlPlaces.Visible = true;        pnlStart.Visible = false;    }    protected void ReturnFromPlaces_Click(object sender, EventArgs e)    {        pnlPlaces.Visible = false;        pnlStart.Visible = true;    }    protected void ReturnFromDeals_Click(object sender, EventArgs e)    {        pnlCoupons.Visible = false;        pnlStart.Visible = true;    }    protected void btnImHereNow_Click(object sender, EventArgs e)    {        long PlaceId = Convert.ToInt32(hdPlaceId.Value);        string UserName = Membership.GetUser().UserName;        string WhatsHappening = txtWhatsHappening.Text;        double UserLat = Convert.ToDouble(Latitude.Value);        double UserLon = Convert.ToDouble(Longitude.Value);        DataAccess da = new DataAccess();        da.StoreUserAT(UserName, PlaceId, WhatsHappening,             UserLat, UserLon);    }    protected void lbImHereNowReturn_Click(object sender, EventArgs e)    {        pnlImHereNow.Visible = false;        pnlPlaces.Visible = true;    }    protected void lbBackToBeginning_Click(object sender, EventArgs e)    {        pnlStart.Visible = true;        pnlImHereNow.Visible = false;    }    protected void lbWhereIveBeen_Click(object sender, EventArgs e)    {        string UserName = Membership.GetUser().UserName;        pnlStart.Visible = false;        pnlIveBeenHere.Visible = true;        DataAccess da = new DataAccess();        lvWhereIveBeen.DataSource = da.UserATs(UserName, 0, 15);        lvWhereIveBeen.DataBind();    }    protected void lbIveBeenHereBack_Click(object sender, EventArgs e)    {        pnlIveBeenHere.Visible = false;        pnlStart.Visible = true;    }     protected void lbPlaceIveBeen_Click(object sender, EventArgs e)    {        LinkButton lb = (LinkButton)sender;        ListViewItem lvi = (ListViewItem)lb.Parent.Parent;        HiddenField hdATID = (HiddenField)lvi.FindControl("hdATID");        Int64 ATID = Convert.ToInt64(hdATID.Value);        DataAccess da = new DataAccess();        pnlIveBeenHere.Visible = false;        pnlPlaceIveBeen.Visible = true;        var plac = da.GetPlaceViaATID(ATID);        hdPlaceIveBeenPlaceId.Value = plac.PlaceId.ToString();        hdPlaceIveBeenLatitude.Value = plac.Latitude.ToString();        hdPlaceIveBeenLongitude.Value = plac.Longitude.ToString();        lblPlaceIveBeenName.Text = plac.Name;        lblPlaceIveBeenAddress.Text = plac.Address1;        lblPlaceIveBeenCity.Text = plac.City;        lblPlaceIveBeenState.Text = plac.Province.ProvinceName;        lblPlaceIveBeenZipCode.Text = plac.ZipCode;        lblPlaceIveBeenCountry.Text = plac.Country.Name;    }     protected void lbNotListed_Click(object sender, EventArgs e)    {        SetupAddPoint();        pnlPlaces.Visible = false;    }     protected void lbAddAPlace_Click(object sender, EventArgs e)    {        SetupAddPoint();    }     private void SetupAddPoint()    {        double lat = Convert.ToDouble(Latitude.Value);        double lon = Convert.ToDouble(Longitude.Value);        DataAccess da = new DataAccess();        var zip = da.WhereAmIAt(lat, lon);        if (zip.Count > 0)        {            var z0 = zip[0];            txtCity.Text = z0.City;            txtZipCode.Text = z0.ZipCode;            ddlProvince.ClearSelection();            if (z0.ProvinceId.HasValue == true)            {                foreach (ListItem li in ddlProvince.Items)                {                    if (li.Value == z0.ProvinceId.Value.ToString())                    {                        li.Selected = true;                        break;                    }                }            }        }        pnlAddPlace.Visible = true;        pnlStart.Visible = false;    }    protected void lbAddPlaceReturn_Click(object sender, EventArgs e)    {        pnlAddPlace.Visible = false;        pnlStart.Visible = true;        liPlaceAddMessage.Visible = false;        PlaceAddMessage.Text = String.Empty;    }    protected void lbPlaceIveBeenBack_Click(object sender, EventArgs e)    {        pnlIveBeenHere.Visible = true;        pnlPlaceIveBeen.Visible = false;            }    protected void lbPlaceIveBeenBeginning_Click(object sender, EventArgs e)    {        pnlPlaceIveBeen.Visible = false;        pnlStart.Visible = true;    }    protected string DisplayName(object val)    {        string strVal = Convert.ToString(val);         if (AppleIPhone.IsIPad())        {            ipd = iPhoneDevice.iPad;        }        if (AppleIPhone.IsIPhone())        {            ipd = iPhoneDevice.iPhone;        }        if (AppleIPhone.IsIPodTouch())        {            ipd = iPhoneDevice.iPodTouch;        }        return (iPhoneHelper.DisplayContentOnMenu(strVal, ipd));    }} iPhoneHelper.cs file: using System;using System.Collections.Generic;using System.Linq;using System.Web; public enum iPhoneDevice{    iPhone, iPodTouch, iPad}/// <summary>/// Summary description for iPhoneHelper/// </summary>/// public class iPhoneHelper{ public iPhoneHelper() {  //  // TODO: Add constructor logic here  // } // This code is stupid in retrospect. Use css to solve this problem      public static string DisplayContentOnMenu(string val, iPhoneDevice ipd)    {        string Return = val;        string Elipsis = "...";        int iPadMaxLength = 30;        int iPhoneMaxLength = 15;        if (ipd == iPhoneDevice.iPad)        {            if (Return.Length > iPadMaxLength)            {                Return = Return.Substring(0, iPadMaxLength - Elipsis.Length) + Elipsis;            }        }        else        {            if (Return.Length > iPhoneMaxLength)            {                Return = Return.Substring(0, iPhoneMaxLength - Elipsis.Length) + Elipsis;            }        }        return (Return);    }}  Source code for the ViewStatePage: using System;using System.Data;using System.Data.SqlClient;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls; /// <summary>/// Summary description for BasePage/// </summary>#region Base class for a page.public class ViewStatePage : System.Web.UI.Page{     PageStatePersisterToDatabase myPageStatePersister;        public ViewStatePage()        : base()    {        myPageStatePersister = new PageStatePersisterToDatabase(this);    }     protected override PageStatePersister PageStatePersister    {        get        {            return myPageStatePersister;        }    } }#endregion #region This class will override the page persistence to store page state in a database.public class PageStatePersisterToDatabase : PageStatePersister{    private string ViewStateKeyField = "__VIEWSTATE_KEY";    private string _exNoConnectionStringFound = "No Database Configuration information is in the web.config.";     public PageStatePersisterToDatabase(Page page)        : base(page)    {    }     public override void Load()    {         // Get the cache key from the web form data        System.Int64 key = Convert.ToInt64(Page.Request.Params[ViewStateKeyField]);         Pair state = this.LoadState(key);         // Abort if cache object is not of type Pair        if (state == null)            throw new ApplicationException("Missing valid " + ViewStateKeyField);         // Set view state and control state        ViewState = state.First;        ControlState = state.Second;    }     public override void Save()    {         // No processing needed if no states available        if (ViewState == null && ControlState != null)            return;         System.Int64 key;        IStateFormatter formatter = this.StateFormatter;        Pair statePair = new Pair(ViewState, ControlState);         // Serialize the statePair object to a string.        string serializedState = formatter.Serialize(statePair);         // Save the ViewState and get a unique identifier back.        key = SaveState(serializedState);         // Register hidden field to store cache key in        // Page.ClientScript does not work properly with Atlas.        //Page.ClientScript.RegisterHiddenField(ViewStateKeyField, key.ToString());        ScriptManager.RegisterHiddenField(this.Page, ViewStateKeyField, key.ToString());    }     private System.Int64 SaveState(string PageState)    {        System.Int64 i64Key = 0;        string strConn = String.Empty,            strProvider = String.Empty;         string strSql = "insert into tblPageState ( SerializedState ) values ( '" + SqlEscape(PageState) + "');select scope_identity();";        SqlConnection sqlCn;        SqlCommand sqlCm;        try        {            GetDBConnectionString(ref strConn, ref strProvider);            sqlCn = new SqlConnection(strConn);            sqlCm = new SqlCommand(strSql, sqlCn);            sqlCn.Open();            i64Key = Convert.ToInt64(sqlCm.ExecuteScalar());            if (sqlCn.State != ConnectionState.Closed)            {                sqlCn.Close();            }            sqlCn.Dispose();            sqlCm.Dispose();        }        finally        {            sqlCn = null;            sqlCm = null;        }        return i64Key;    }     private Pair LoadState(System.Int64 iKey)    {        string strConn = String.Empty,            strProvider = String.Empty,            SerializedState = String.Empty,            strMinutesInPast = GetMinutesInPastToDelete();        Pair PageState;        string strSql = "select SerializedState from tblPageState where tblPageStateID=" + iKey.ToString() + ";" +            "delete from tblPageState where DateUpdated<DateAdd(mi, " + strMinutesInPast + ", getdate());";        SqlConnection sqlCn;        SqlCommand sqlCm;        try        {            GetDBConnectionString(ref strConn, ref strProvider);            sqlCn = new SqlConnection(strConn);            sqlCm = new SqlCommand(strSql, sqlCn);             sqlCn.Open();            SerializedState = Convert.ToString(sqlCm.ExecuteScalar());            IStateFormatter formatter = this.StateFormatter;             if ((null == SerializedState) ||                (String.Empty == SerializedState))            {                throw (new ApplicationException("No ViewState records were returned."));            }             // Deserilize returns the Pair object that is serialized in            // the Save method.            PageState = (Pair)formatter.Deserialize(SerializedState);             if (sqlCn.State != ConnectionState.Closed)            {                sqlCn.Close();            }            sqlCn.Dispose();            sqlCm.Dispose();        }        finally        {            sqlCn = null;            sqlCm = null;        }        return PageState;    }     private string SqlEscape(string Val)    {        string ReturnVal = String.Empty;        if (null != Val)        {            ReturnVal = Val.Replace("'", "''");        }        return (ReturnVal);    }    private void GetDBConnectionString(ref string ConnectionStringValue, ref string ProviderNameValue)    {        if (System.Configuration.ConfigurationManager.ConnectionStrings.Count > 0)        {            ConnectionStringValue = System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;            ProviderNameValue = System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ProviderName;        }        else        {            throw new ConfigurationErrorsException(_exNoConnectionStringFound);        }    }    private string GetMinutesInPastToDelete()    {        string strReturn = "-60";        if (null != System.Configuration.ConfigurationManager.AppSettings["MinutesInPastToDeletePageState"])        {            strReturn = System.Configuration.ConfigurationManager.AppSettings["MinutesInPastToDeletePageState"].ToString();        }        return (strReturn);    }}#endregion AppleiPhone.cs file: using System;using System.Collections.Generic;using System.Linq;using System.Web; /// <summary>/// Summary description for AppleIPhone/// </summary>public class AppleIPhone{ public AppleIPhone() {  //  // TODO: Add constructor logic here  // }     static public bool IsIPhoneOS()    {        return (IsIPad() || IsIPhone() || IsIPodTouch());    }     static public bool IsIPhone()    {        return IsTest("iPhone");    }     static public bool IsIPodTouch()    {        return IsTest("iPod");    }     static public bool IsIPad()    {        return IsTest("iPad");    }     static private bool IsTest(string Agent)    {        bool bl = false;        string ua = HttpContext.Current.Request.UserAgent.ToLower();        try        {            bl = ua.Contains(Agent.ToLower());        }        catch { }        return (bl);        }} Master page .cs: using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls; public partial class MasterPages_iPhoneMaster : System.Web.UI.MasterPage{    protected void Page_Load(object sender, EventArgs e)    {            HtmlHead head = Page.Header;            HtmlMeta meta = new HtmlMeta();            if (AppleIPhone.IsIPad() == true)            {                meta.Content = "width=400,user-scalable=no";                head.Controls.Add(meta);             }            else            {                meta.Content = "width=device-width, user-scalable=no";                meta.Attributes.Add("name", "viewport");            }            meta.Attributes.Add("name", "viewport");            head.Controls.Add(meta);            HtmlLink cssLink = new HtmlLink();            HtmlGenericControl script = new HtmlGenericControl("script");            script.Attributes.Add("type", "text/javascript");            script.Attributes.Add("src", ResolveUrl("~/Scripts/iWebKit/javascript/functions.js"));            head.Controls.Add(script);            cssLink.Attributes.Add("rel", "stylesheet");            cssLink.Attributes.Add("href", ResolveUrl("~/Scripts/iWebKit/css/style.css") );            cssLink.Attributes.Add("type", "text/css");            head.Controls.Add(cssLink);            HtmlGenericControl jsLink = new HtmlGenericControl("script");            //jsLink.Attributes.Add("type", "text/javascript");            //jsLink.Attributes.Add("src", ResolveUrl("~/Scripts/jquery-1.4.1.min.js") );            //head.Controls.Add(jsLink);            HtmlLink appleIcon = new HtmlLink();            appleIcon.Attributes.Add("rel", "apple-touch-icon");            appleIcon.Attributes.Add("href", ResolveUrl("~/apple-touch-icon.png"));            HtmlMeta appleMobileWebAppStatusBarStyle = new HtmlMeta();            appleMobileWebAppStatusBarStyle.Attributes.Add("name", "apple-mobile-web-app-status-bar-style");            appleMobileWebAppStatusBarStyle.Attributes.Add("content", "black");            head.Controls.Add(appleMobileWebAppStatusBarStyle);    }     internal string FindPath(string Location)    {        string Url = Server.MapPath(Location);        return (Url);    }}

    Read the article

  • Automating Solaris 11 Zones Installation Using The Automated Install Server

    - by Orgad Kimchi
    Introduction How to use the Oracle Solaris 11 Automated install server in order to automate the Solaris 11 Zones installation. In this document I will demonstrate how to setup the Automated Install server in order to provide hands off installation process for the Global Zone and two Non Global Zones located on the same system. Architecture layout: Figure 1. Architecture layout Prerequisite Setup the Automated install server (AI) using the following instructions “How to Set Up Automated Installation Services for Oracle Solaris 11” The first step in this setup will be creating two Solaris 11 Zones configuration files. Step 1: Create the Solaris 11 Zones configuration files  The Solaris Zones configuration files should be in the format of the zonecfg export command. # zonecfg -z zone1 export > /var/tmp/zone1# cat /var/tmp/zone1 create -b set brand=solaris set zonepath=/rpool/zones/zone1 set autoboot=true set ip-type=exclusive add anet set linkname=net0 set lower-link=auto set configure-allowed-address=true set link-protection=mac-nospoof set mac-address=random end  Create a backup copy of this file under a different name, for example, zone2. # cp /var/tmp/zone1 /var/tmp/zone2 Modify the second configuration file with the zone2 configuration information You should change the zonepath for example: set zonepath=/rpool/zones/zone2 Step2: Copy and share the Zones configuration files  Create the NFS directory for the Zones configuration files # mkdir /export/zone_config Share the directory for the Zones configuration file # share –o ro /export/zone_config Copy the Zones configuration files into the NFS shared directory # cp /var/tmp/zone1 /var/tmp/zone2  /export/zone_config Verify that the NFS share has been created using the following command # share export_zone_config      /export/zone_config     nfs     sec=sys,ro Step 3: Add the Global Zone as client to the Install Service Use the installadm create-client command to associate client (Global Zone) with the install service To find the MAC address of a system, use the dladm command as described in the dladm(1M) man page. The following command adds the client (Global Zone) with MAC address 0:14:4f:2:a:19 to the s11x86service install service. # installadm create-client -e “0:14:4f:2:a:19" -n s11x86service You can verify the client creation using the following command # installadm list –c Service Name  Client Address     Arch   Image Path ------------  --------------     ----   ---------- s11x86service 00:14:4F:02:0A:19  i386   /export/auto_install/s11x86service We can see the client install service name (s11x86service), MAC address (00:14:4F:02:0A:19 and Architecture (i386). Step 4: Global Zone manifest setup  First, get a list of the installation services and the manifests associated with them: # installadm list -m Service Name   Manifest        Status ------------   --------        ------ default-i386   orig_default   Default s11x86service  orig_default   Default Then probe the s11x86service and the default manifest associated with it. The -m switch reflects the name of the manifest associated with a service. Since we want to capture that output into a file, we redirect the output of the command as follows: # installadm export -n s11x86service -m orig_default >  /var/tmp/orig_default.xml Create a backup copy of this file under a different name, for example, orig-default2.xml, and edit the copy. # cp /var/tmp/orig_default.xml /var/tmp/orig_default2.xml Use the configuration element in the AI manifest for the client system to specify non-global zones. Use the name attribute of the configuration element to specify the name of the zone. Use the source attribute to specify the location of the config file for the zone.The source location can be any http:// or file:// location that the client can access during installation. The following sample AI manifest specifies two Non-Global Zones: zone1 and zone2 You should replace the server_ip with the ip address of the NFS server. <!DOCTYPE auto_install SYSTEM "file:///usr/share/install/ai.dtd.1"> <auto_install>   <ai_instance>     <target>       <logical>         <zpool name="rpool" is_root="true">           <filesystem name="export" mountpoint="/export"/>           <filesystem name="export/home"/>           <be name="solaris"/>         </zpool>       </logical>     </target>     <software type="IPS">       <source>         <publisher name="solaris">           <origin name="http://pkg.oracle.com/solaris/release"/>         </publisher>       </source>       <software_data action="install">         <name>pkg:/entire@latest</name>         <name>pkg:/group/system/solaris-large-server</name>       </software_data>     </software>     <configuration type="zone" name="zone1" source="file:///net/server_ip/export/zone_config/zone1"/>     <configuration type="zone" name="zone2" source="file:///net/server_ip/export/zone_config/zone2"/>   </ai_instance> </auto_install> The following example adds the /var/tmp/orig_default2.xml AI manifest to the s11x86service install service # installadm create-manifest -n s11x86service -f /var/tmp/orig_default2.xml -m gzmanifest You can verify the manifest creation using the following command # installadm list -n s11x86service  -m Service/Manifest Name  Status   Criteria ---------------------  ------   -------- s11x86service    orig_default        Default  None    gzmanifest          Inactive None We can see from the command output that the new manifest named gzmanifest has been created and associated with the s11x86service install service. Step 5: Non Global Zone manifest setup The AI manifest for non-global zone installation is similar to the AI manifest for installing the global zone. If you do not provide a custom AI manifest for a non-global zone, the default AI manifest for Zones is used The default AI manifest for Zones is available at /usr/share/auto_install/manifest/zone_default.xml. In this example we should use the default AI manifest for zones The following sample default AI manifest for zones # cat /usr/share/auto_install/manifest/zone_default.xml <?xml version="1.0" encoding="UTF-8"?> <!--  Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. --> <!DOCTYPE auto_install SYSTEM "file:///usr/share/install/ai.dtd.1"> <auto_install>     <ai_instance name="zone_default">         <target>             <logical>                 <zpool name="rpool">                     <!--                       Subsequent <filesystem> entries instruct an installer                       to create following ZFS datasets:                           <root_pool>/export         (mounted on /export)                           <root_pool>/export/home    (mounted on /export/home)                       Those datasets are part of standard environment                       and should be always created.                       In rare cases, if there is a need to deploy a zone                       without these datasets, either comment out or remove                       <filesystem> entries. In such scenario, it has to be also                       assured that in case of non-interactive post-install                       configuration, creation of initial user account is                       disabled in related system configuration profile.                       Otherwise the installed zone would fail to boot.                     -->                     <filesystem name="export" mountpoint="/export"/>                     <filesystem name="export/home"/>                     <be name="solaris">                         <options>                             <option name="compression" value="on"/>                         </options>                     </be>                 </zpool>             </logical>         </target>         <software type="IPS">             <destination>                 <image>                     <!-- Specify locales to install -->                     <facet set="false">facet.locale.*</facet>                     <facet set="true">facet.locale.de</facet>                     <facet set="true">facet.locale.de_DE</facet>                     <facet set="true">facet.locale.en</facet>                     <facet set="true">facet.locale.en_US</facet>                     <facet set="true">facet.locale.es</facet>                     <facet set="true">facet.locale.es_ES</facet>                     <facet set="true">facet.locale.fr</facet>                     <facet set="true">facet.locale.fr_FR</facet>                     <facet set="true">facet.locale.it</facet>                     <facet set="true">facet.locale.it_IT</facet>                     <facet set="true">facet.locale.ja</facet>                     <facet set="true">facet.locale.ja_*</facet>                     <facet set="true">facet.locale.ko</facet>                     <facet set="true">facet.locale.ko_*</facet>                     <facet set="true">facet.locale.pt</facet>                     <facet set="true">facet.locale.pt_BR</facet>                     <facet set="true">facet.locale.zh</facet>                     <facet set="true">facet.locale.zh_CN</facet>                     <facet set="true">facet.locale.zh_TW</facet>                 </image>             </destination>             <software_data action="install">                 <name>pkg:/group/system/solaris-small-server</name>             </software_data>         </software>     </ai_instance> </auto_install> (optional) We can customize the default AI manifest for Zones Create a backup copy of this file under a different name, for example, zone_default2.xml and edit the copy # cp /usr/share/auto_install/manifest/zone_default.xml /var/tmp/zone_default2.xml Edit the copy (/var/tmp/zone_default2.xml) The following example adds the /var/tmp/zone_default2.xml AI manifest to the s11x86service install service and specifies that zone1 and zone2 should use this manifest. # installadm create-manifest -n s11x86service -f /var/tmp/zone_default2.xml -m zones_manifest -c zonename="zone1 zone2" Note: Do not use the following elements or attributes in a non-global zone AI manifest:     The auto_reboot attribute of the ai_instance element     The http_proxy attribute of the ai_instance element     The disk child element of the target element     The noswap attribute of the logical element     The nodump attribute of the logical element     The configuration element Step 6: Global Zone profile setup We are going to create a global zone configuration profile which includes the host information for example: host name, ip address name services etc… # sysconfig create-profile –o /var/tmp/gz_profile.xml You need to provide the host information for example:     Default router     Root password     DNS information The output should eventually disappear and be replaced by the initial screen of the System Configuration Tool (see Figure 2), where you can do the final configuration. Figure 2. Profile creation menu You can validate the profile using the following command # installadm validate -n s11x86service –P /var/tmp/gz_profile.xml Validating static profile gz_profile.xml...  Passed Next, instantiate a profile with the install service. In our case, use the following syntax for doing this # installadm create-profile -n s11x86service  -f /var/tmp/gz_profile.xml -p  gz_profile You can verify profile creation using the following command # installadm list –n s11x86service  -p Service/Profile Name  Criteria --------------------  -------- s11x86service    gz_profile         None We can see that the gz_profie has been created and associated with the s11x86service Install service. Step 7: Setup the Solaris Zones configuration profiles The step should be similar to the Global zone profile creation on step 6 # sysconfig create-profile –o /var/tmp/zone1_profile.xml # sysconfig create-profile –o /var/tmp/zone2_profile.xml You can validate the profiles using the following command # installadm validate -n s11x86service -P /var/tmp/zone1_profile.xml Validating static profile zone1_profile.xml...  Passed # installadm validate -n s11x86service -P /var/tmp/zone2_profile.xml Validating static profile zone2_profile.xml...  Passed Next, associate the profiles with the install service The following example adds the zone1_profile.xml configuration profile to the s11x86service  install service and specifies that zone1 should use this profile. # installadm create-profile -n s11x86service  -f  /var/tmp/zone1_profile.xml -p zone1_profile -c zonename=zone1 The following example adds the zone2_profile.xml configuration profile to the s11x86service  install service and specifies that zone2 should use this profile. # installadm create-profile -n s11x86service  -f  /var/tmp/zone2_profile.xml -p zone2_profile -c zonename=zone2 You can verify the profiles creation using the following command # installadm list -n s11x86service -p Service/Profile Name  Criteria --------------------  -------- s11x86service    zone1_profile      zonename = zone1    zone2_profile      zonename = zone2    gz_profile         None We can see that we have three profiles in the s11x86service  install service     Global Zone  gz_profile     zone1            zone1_profile     zone2            zone2_profile. Step 8: Global Zone setup Associate the global zone client with the manifest and the profile that we create in the previous steps The following example adds the manifest and profile to the client (global zone), where: gzmanifest  is the name of the manifest. gz_profile  is the name of the configuration profile. mac="0:14:4f:2:a:19" is the client (global zone) mac address s11x86service is the install service name. # installadm set-criteria -m  gzmanifest  –p  gz_profile  -c mac="0:14:4f:2:a:19" -n s11x86service You can verify the manifest and profile association using the following command # installadm list -n s11x86service -p  -m Service/Manifest Name  Status   Criteria ---------------------  ------   -------- s11x86service    gzmanifest                   mac  = 00:14:4F:02:0A:19    orig_default        Default  None Service/Profile Name  Criteria --------------------  -------- s11x86service    gz_profile         mac      = 00:14:4F:02:0A:19    zone2_profile      zonename = zone2    zone1_profile      zonename = zone1 Step 9: Provision the host with the Non-Global Zones The next step is to boot the client system off the network and provision it using the Automated Install service that we just set up. First, boot the client system. Figure 3 shows the network boot attempt (when done on an x86 system): Figure 3. Network Boot Then you will be prompted by a GRUB menu, with a timer, as shown in Figure 4. The default selection (the "Text Installer and command line" option) is highlighted.  Press the down arrow to highlight the second option labeled Automated Install, and then press Enter. The reason we need to do this is because we want to prevent a system from being automatically re-installed if it were to be booted from the network accidentally. Figure 4. GRUB Menu What follows is the continuation of a networked boot from the Automated Install server,. The client downloads a mini-root (a small set of files in which to successfully run the installer), identifies the location of the Automated Install manifest on the network, retrieves that manifest, and then processes it to identify the address of the IPS repository from which to obtain the desired software payload. Non-Global Zones are installed and configured on the first reboot after the Global Zone is installed. You can list all the Solaris Zones status using the following command # zoneadm list -civ Once the Zones are in running state you can login into the Zone using the following command # zlogin –z zone1 Troubleshooting Automated Installations If an installation to a client system failed, you can find the client log at /system/volatile/install_log. NOTE: Zones are not installed if any of the following errors occurs:     A zone config file is not syntactically correct.     A collision exists among zone names, zone paths, or delegated ZFS datasets in the set of zones to be installed     Required datasets are not configured in the global zone. For more troubleshooting information see “Installing Oracle Solaris 11 Systems” Conclusion This paper demonstrated the benefits of using the Automated Install server to simplify the Non Global Zones setup, including the creation and configuration of the global zone manifest and the Solaris Zones profiles.

    Read the article

< Previous Page | 21 22 23 24 25 26 27 28 29 30 31 32  | Next Page >