Whatever message this page gives is out now! Go check it out!
<cfset filename = expandpath('./myfile.txt')> <cftry> <cffile action="write" file="#filename#"> some tag body </cffile> <cfset content = FileRead(filename)> <cfoutput>File Length = #Len(content)#</cfoutput> <cfcatch type="any"> <cfoutput> #cfcatch.message# <br>#cfcatch.detail# <br> </cfoutput> </cfcatch> </cftry> |
<!--- Leave a blank line here---> </cffile> |
<cfset variables.URL = "http://#cgi.server_name#:#cgi.server_port## getDirectoryFromPath(cgi.script_name)#_upload.cfm"> <cfhttp method="Post" url="#variables.URL#"> <cfhttpparam type="FILE" name="myfile" file="#expandpath('./sample.txt')#"> </cfhttp> <cfoutput>#cfhttp.filecontent#</cfoutput> <cfcatch> <cfoutput> #CFCATCH.message# <br>#CFCATCH.detail# <br> </cfoutput> </cfcatch> </cftry> |
<!--- create upload directory ---> <cfif not directoryExists(uploadDirectory)> <cfdirectory action="create" directory="#uploadDirectory#"> </cfif> <cftry> <cffile action="UPLOAD" destination="#uploadDirectory#" filefield="form.myFile" nameconflict="MAKEUNIQUE" accept=".txt"> <cfcatch> <cfoutput> #CFCATCH.message# <br>#CFCATCH.detail# <br> </cfoutput> </cfcatch> </cftry> <!--- read directory ---> <cfdirectory action="LIST" directory="#uploadDirectory#" name="qFileList"> <cfoutput>#qFileList.recordcount# file(s) uploaded <br> </cfoutput> <!--- delete all the uploaded files---> <!--- <cfloop query="qFileList"> <cffile action="delete" file="#uploadDirectory#/#Name#"> </cfloop> ---> <!--- delete directory ---> <!--- <cfdirectory action="delete" directory="#uploadDirectory#"> ---> |
destination="#uploadDirectory#" filefield="form.myFile" nameconflict="MAKEUNIQUE " accept="application/pdf " strict=true> |
<cfhttpparam type="FILE" name="myfile" file="#expandpath('./sample.txt')#"> |
action="UPLOAD" destination="#uploadDirectory#" filefield="form.myFile" nameconflict="MAKEUNIQUE" accept=".txt, application/pdf" strict=true> |
<cfhttpparam type="FILE" name="myfile" file="#expandpath('./sample.txt')#"> |
This is a view-only example. ---> <!--- <cfif IsDefined("form.formsubmit") is "Yes"> <!--- The form has been submitted, now do the action. ---> <cfif form.action is "new"> <!--- Make a new file. ---> <cffile action="Write" file="#GetTempDirectory()#foobar.txt" output="#form.the_text#"> </cfif> <cfif form.action is "read"> <!--- Read existing file. ---> <cffile action="Read" file="#GetTempDirectory()#foobar.txt" variable="readText"> </cfif> <cfif form.action is "add"> <!--- Update existing file. ---> <cffile action="Append" file="#GetTempDirectory()#foobar.txt" output="#form.the_text#"> </cfif> <cfif form.action is "delete"> <!--- Delete existing fil. ---> <cffile action="Delete" file="#GetTempDirectory()#foobar.txt"> </cfif> </cfif> <!--- Set some variables. ---> <cfparam name="fileExists" default="no"> <cfparam name="readText" default=""> <!--- First, check whether canned file exists. ---> <cfif FileExists("#GetTempDirectory()#foobar.txt") is "Yes"> <cfset fileExists="yes"> </cfif> <!--- Now, make the form that runs the example. ---> <form action="index.cfm" method="POST"> <h4>Type in some text to include in your file:</h4> <p> <cfif fileExists is "yes"> <p>A file exists (foobar.txt, in <cfoutput>#GetTempDirectory()#</cfoutput>). You may add to it, read from it, or delete it. </p> </cfif> <!--- If reading from a form, let that information display in textarea. ---> <textarea name="the_text" cols="40" rows="5"> <cfif readText is not ""> <cfoutput>#readText#</cfoutput> </cfif></textarea> <!--- Select from the actions depending on whether the file exists. ---> <select name="action"> <cfif fileExists is "no"> <option value="new">Make new file </cfif> <cfif fileExists is "yes"> <option value="add">Add to existing file <option value="delete">Delete file <option value="read">Read existing file </cfif> </select> <input type="Hidden" name="formsubmit" value="yes"> <input type="Submit" name="" value="make my changes"> </form> ---> |
<cfscript>
  // Configuration
  uploadDir = expandPath("./uploads/");
  maxFileSize = 10485760; // 10MB in bytes
  allowedTypes = "application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  Â
  // Create upload directory if it doesn't exist
  try {
    if (!directoryExists(uploadDir)) {
      directoryCreate(uploadDir);
    }
    canUpload = true;
  } catch (any e) {
    canUpload = false;
    uploadDir = "File system access not available";
  }
</cfscript>
<h2>Secure File Upload with Validation</h2>
<cfif NOT canUpload>
  <div style="background: ##fff3e0; border: 2px solid ##ff9800; padding: 20px; margin: 20px 0; border-radius: 5px;">
    <h3 style="color: orange; margin: 0;">⚠File Upload Not Available</h3>
    <p>The application doesn't have permission to create upload directories.</p>
    <p><strong>For production:</strong> Configure a directory with proper write permissions.</p>
  </div>
</cfif>
<!--- Upload Form --->
<cfif NOT isDefined("form.documentFile") AND canUpload>
  Â
  <div style="background: ##e3f2fd; border: 2px solid ##2196f3; padding: 20px; margin: 20px 0; border-radius: 5px;">
    <h3>Upload Document</h3>
    <p>Accepted file types: PDF, Word (.doc, .docx), Excel (.xls, .xlsx)</p>
    <p><strong>Maximum file size:</strong> 10 MB</p>
  </div>
  Â
  <form method="post" enctype="multipart/form-data">
    <div style="margin: 20px 0;">
      <label for="documentFile"><strong>Select File:</strong></label><br>
      <input type="file" name="documentFile" id="documentFile" required>
    </div>
    Â
    <div style="margin: 20px 0;">
      <label for="category"><strong>Category:</strong></label><br>
      <select name="category" id="category">
        <option value="contracts">Contracts</option>
        <option value="invoices">Invoices</option>
        <option value="proposals">Proposals</option>
        <option value="other">Other</option>
      </select>
    </div>
    Â
    <div>
      <button type="submit" style="padding: 10px 20px; background: ##2196f3; color: white; border: none; border-radius: 5px; cursor: pointer;">
        Upload Document
      </button>
    </div>
  </form>
  Â
<cfelseif isDefined("form.documentFile") AND canUpload>
  Â
  <!--- Process File Upload --->
  <h3>Processing Upload...</h3>
  Â
  <cftry>
    <!--- Upload the file with validation --->
    <cffileÂ
      action="upload"Â
      fileField="documentFile"Â
      destination="#uploadDir#"Â
      nameConflict="makeunique"
      accept="#allowedTypes#"
      strict="true"
      result="uploadResult">
    Â
    <!--- Get file information --->
    <cfset uploadedFilePath = uploadResult.serverDirectory & "/" & uploadResult.serverFile>
    <cfset fileInfo = getFileInfo(uploadedFilePath)>
    Â
    <!--- Validate file size --->
    <cfif uploadResult.fileSize GT maxFileSize>
      <!--- File too large, delete it --->
      <cffile action="delete" file="#uploadedFilePath#">
      Â
      <div style="background: ##ffebee; border: 2px solid ##f44336; padding: 20px; margin: 20px 0; border-radius: 5px;">
        <h3 style="color: red; margin: 0;">✗ Upload Failed</h3>
        <p><strong>Error:</strong> File size exceeds maximum allowed size.</p>
        <p><strong>File size:</strong> #numberFormat(uploadResult.fileSize / 1024 / 1024, "0.00")# MB</p>
        <p><strong>Maximum allowed:</strong> #numberFormat(maxFileSize / 1024 / 1024, "0.00")# MB</p>
      </div>
      Â
    <cfelse>
      <!--- Upload successful --->
      <div style="background: ##e8f5e9; border: 2px solid ##4caf50; padding: 20px; margin: 20px 0; border-radius: 5px;">
        <h3 style="color: green; margin: 0;">✓ Upload Successful!</h3>
        <p>Your file has been uploaded successfully.</p>
      </div>
      Â
      <!--- Display upload details --->
      <h3>Upload Details</h3>
      <cfdumpÂ
        var="#uploadResult#"Â
        label="Upload Result"
        expand="yes">
      Â
      <h3>File Information</h3>
      <cfscript>
        uploadDetails = {};
        uploadDetails.originalFilename = uploadResult.clientFile;
        uploadDetails.serverFilename = uploadResult.serverFile;
        uploadDetails.fileSize = numberFormat(uploadResult.fileSize / 1024, "0.00") & " KB";
        uploadDetails.mimeType = uploadResult.contentType & "/" & uploadResult.contentSubType;
        uploadDetails.fileExtension = uploadResult.serverFileExt;
        uploadDetails.uploadDate = dateTimeFormat(fileInfo.lastModified, "yyyy-mm-dd HH:nn:ss");
        uploadDetails.category = form.category;
        uploadDetails.fileSaved = uploadResult.fileWasSaved;
      </cfscript>
      Â
      <cfdumpÂ
        var="#uploadDetails#"Â
        label="File Details"
        expand="yes">
      Â
      <!--- In production, save upload info to database --->
      <div style="background: ##e3f2fd; border: 2px solid ##2196f3; padding: 15px; margin: 15px 0; border-radius: 5px;">
        <h4>💡 Production Note</h4>
        <p>In a production environment, you would:</p>
        <ul>
          <li>Save file metadata to database</li>
          <li>Associate file with user ID</li>
          <li>Run virus scanning on uploaded file</li>
          <li>Generate download/access tokens</li>
          <li>Log upload activity for audit</li>
        </ul>
      </div>
    </cfif>
    Â
    <p><a href="?" style="padding: 10px 20px; background: ##2196f3; color: white; text-decoration: none; border-radius: 5px; display: inline-block; margin-top: 20px;">
      Upload Another File
    </a></p>
    Â
    <cfcatch type="any">
      <div style="background: ##ffebee; border: 2px solid ##f44336; padding: 20px; margin: 20px 0; border-radius: 5px;">
        <h3 style="color: red; margin: 0;">✗ Upload Failed</h3>
        <p><strong>Error:</strong> #cfcatch.message#</p>
        <p><strong>Detail:</strong> #cfcatch.detail#</p>
        <p>Please ensure you're uploading a valid file type.</p>
      </div>
      Â
      <p><a href="?">Try Again</a></p>
    </cfcatch>
  </cftry>
  Â
</cfif>
<cfscript>
  // Configuration
  logDir = expandPath("./logs/");
  todayDate = dateFormat(now(), "yyyy-mm-dd");
  currentLogFile = logDir & "app_log_" & todayDate & ".txt";
  Â
  // Create logs directory if it doesn't exist
  try {
    if (!directoryExists(logDir)) {
      directoryCreate(logDir);
    }
    canAccessLogs = true;
  } catch (any e) {
    canAccessLogs = false;
    errorMessage = e.message;
  }
  Â
  // Function to format log entry
  function formatLogEntry(logType, message) {
    timestamp = dateTimeFormat(now(), "yyyy-mm-dd HH:nn:ss");
    logEntry = "#timestamp# [#uCase(logType)#] #message#" & chr(13) & chr(10);
    return logEntry;
  }
</cfscript>
<h2>Application Log File Management</h2>
<cfif NOT canAccessLogs>
  <div style="background: ##fff3e0; border: 2px solid ##ff9800; padding: 20px; margin: 20px 0; border-radius: 5px;">
    <h3 style="color: orange; margin: 0;">⚠Log Files Not Available</h3>
    <p>Unable to access log directory: <strong>#errorMessage#</strong></p>
    <p>This example demonstrates the log management functionality.</p>
  </div>
</cfif>
<!--- Handle form submissions --->
<cfif isDefined("form.action") AND canAccessLogs>
  Â
  <cftry>
    <cfif form.action EQ "addLog">
      <!--- Append new log entry --->
      <cfset newLogEntry = formatLogEntry(form.logType, form.logMessage)>
      Â
      <!--- Check if file exists, if not create it with header --->
      <cfif NOT fileExists(currentLogFile)>
        <cfset logHeader = "Application Log - Started: #dateTimeFormat(now(), 'yyyy-mm-dd HH:nn:ss')#" & chr(13) & chr(10) &Â
                  "============================================" & chr(13) & chr(10)>
        <cffile action="write" file="#currentLogFile#" output="#logHeader#">
      </cfif>
      Â
      <!--- Append the log entry --->
      <cffile action="append" file="#currentLogFile#" output="#newLogEntry#">
      Â
      <div style="background: ##e8f5e9; border: 2px solid ##4caf50; padding: 15px; margin: 20px 0; border-radius: 5px;">
        <strong>✓ Log Entry Added Successfully</strong>
      </div>
      Â
    <cfelseif form.action EQ "clearLog">
      <!--- Delete current log file --->
      <cfif fileExists(currentLogFile)>
        <cffile action="delete" file="#currentLogFile#">
        <div style="background: ##e8f5e9; border: 2px solid ##4caf50; padding: 15px; margin: 20px 0; border-radius: 5px;">
          <strong>✓ Log File Cleared Successfully</strong>
        </div>
      </cfif>
    </cfif>
    Â
    <cfcatch type="any">
      <div style="background: ##ffebee; border: 2px solid ##f44336; padding: 15px; margin: 20px 0; border-radius: 5px;">
        <strong>✗ Error:</strong> #cfcatch.message#
      </div>
    </cfcatch>
  </cftry>
  Â
</cfif>
<!--- Add Log Entry Form --->
<cfif canAccessLogs>
  <div style="background: ##e3f2fd; border: 2px solid ##2196f3; padding: 20px; margin: 20px 0; border-radius: 5px;">
    <h3>Add New Log Entry</h3>
    Â
    <form method="post">
      <input type="hidden" name="action" value="addLog">
      Â
      <div style="margin: 15px 0;">
        <label for="logType"><strong>Log Type:</strong></label><br>
        <select name="logType" id="logType" style="padding: 5px; width: 200px;">
          <option value="info">INFO</option>
          <option value="warning">WARNING</option>
          <option value="error">ERROR</option>
          <option value="debug">DEBUG</option>
          <option value="audit">AUDIT</option>
        </select>
      </div>
      Â
      <div style="margin: 15px 0;">
        <label for="logMessage"><strong>Log Message:</strong></label><br>
        <textarea name="logMessage" id="logMessage" rows="3" style="width: 100%; max-width: 600px; padding: 8px;" placeholder="Enter your log message here..." required></textarea>
      </div>
      Â
      <div>
        <button type="submit" style="padding: 10px 20px; background: ##2196f3; color: white; border: none; border-radius: 5px; cursor: pointer;">
          Add Log Entry
        </button>
      </div>
    </form>
  </div>
</cfif>
<!--- Display Current Log File --->
<cfif canAccessLogs>
  <h3>Current Log File: <code>app_log_#todayDate#.txt</code></h3>
  Â
  <cfif fileExists(currentLogFile)>
    <!--- Read the log file --->
    <cftry>
      <cffile action="read" file="#currentLogFile#" variable="logContents">
      Â
      <!--- Get file info --->
      <cfset logFileInfo = getFileInfo(currentLogFile)>
      Â
      <div style="background: ##f5f5f5; border: 1px solid ##ccc; padding: 15px; margin: 15px 0; border-radius: 5px;">
        <strong>File Size:</strong> #numberFormat(logFileInfo.size / 1024, "0.00")# KB |Â
        <strong>Last Modified:</strong> #dateTimeFormat(logFileInfo.lastModified, "yyyy-mm-dd HH:nn:ss")# |Â
        <strong>Lines:</strong> #listLen(logContents, chr(10))#
      </div>
      Â
      <!--- Display log contents --->
      <div style="background: ##263238; color: ##aed581; padding: 20px; border-radius: 5px; overflow-x: auto; font-family: 'Courier New', monospace; font-size: 14px; max-height: 500px; overflow-y: auto;">
        <pre style="margin: 0; white-space: pre-wrap;"><cfoutput>#htmlEditFormat(logContents)#</cfoutput></pre>
      </div>
      Â
      <!--- Clear log button --->
      <form method="post" style="margin-top: 15px;" onsubmit="return confirm('Are you sure you want to clear this log file?');">
        <input type="hidden" name="action" value="clearLog">
        <button type="submit" style="padding: 10px 20px; background: ##f44336; color: white; border: none; border-radius: 5px; cursor: pointer;">
          Clear Log File
        </button>
      </form>
      Â
      <cfcatch type="any">
        <div style="background: ##ffebee; border: 2px solid ##f44336; padding: 15px; margin: 15px 0; border-radius: 5px;">
          <strong>Error reading log file:</strong> #cfcatch.message#
        </div>
      </cfcatch>
    </cftry>
  <cfelse>
    <div style="background: ##fff3e0; border: 2px solid ##ff9800; padding: 15px; margin: 15px 0; border-radius: 5px;">
      <strong>ℹ No log file exists for today.</strong> Add a log entry to create one.
    </div>
  </cfif>
</cfif>
<!--- List All Log Files --->
<cfif canAccessLogs>
  <h3>Log File Archive</h3>
  Â
  <cftry>
    <cfset logFiles = directoryList(logDir, false, "query", "app_log_*.txt", "dateLastModified desc")>
    Â
    <cfif logFiles.recordCount GT 0>
      <table style="width: 100%; border-collapse: collapse; margin: 15px 0;">
        <thead>
          <tr style="background: ##e0e0e0;">
            <th style="padding: 10px; border: 1px solid ##ccc; text-align: left;">Log File</th>
            <th style="padding: 10px; border: 1px solid ##ccc; text-align: left;">Size</th>
            <th style="padding: 10px; border: 1px solid ##ccc; text-align: left;">Last Modified</th>
          </tr>
        </thead>
        <tbody>
          <cfoutput query="logFiles">
            <tr>
              <td style="padding: 10px; border: 1px solid ##ccc;">#name#</td>
              <td style="padding: 10px; border: 1px solid ##ccc;">#numberFormat(size / 1024, "0.00")# KB</td>
              <td style="padding: 10px; border: 1px solid ##ccc;">#dateTimeFormat(dateLastModified, "yyyy-mm-dd HH:nn:ss")#</td>
            </tr>
          </cfoutput>
        </tbody>
      </table>
    <cfelse>
      <p><em>No log files found.</em></p>
    </cfif>
    Â
    <cfcatch type="any">
      <p><em>Unable to list log files.</em></p>
    </cfcatch>
  </cftry>
</cfif>
<cfscript>
  // Configuration
  configDir = expandPath("./config/");
  configFile = configDir & "app_settings.json";
  backupDir = configDir & "backups/";
  Â
  // Create directories if they don't exist
  try {
    if (!directoryExists(configDir)) {
      directoryCreate(configDir);
    }
    if (!directoryExists(backupDir)) {
      directoryCreate(backupDir);
    }
    canAccessConfig = true;
  } catch (any e) {
    canAccessConfig = false;
    errorMessage = e.message;
  }
  Â
  // Default configuration structure
  function getDefaultConfig() {
    config = {};
    config.appName = "My ColdFusion App";
    config.version = "1.0.0";
    Â
    config.branding = {};
    config.branding.primaryColor = "##2196f3";
    config.branding.secondaryColor = "##ff9800";
    config.branding.logo = "logo.png";
    Â
    config.features = {};
    config.features.enableChat = true;
    config.features.enableNotifications = true;
    config.features.enableAnalytics = false;
    Â
    config.email = {};
    config.email.fromAddress = "noreply@example.com";
    config.email.smtpServer = "smtp.example.com";
    config.email.smtpPort = 587;
    Â
    config.lastUpdated = dateTimeFormat(now(), "yyyy-mm-dd HH:nn:ss");
    config.updatedBy = "system";
    Â
    return config;
  }
  Â
  // Load configuration from file
  function loadConfig() {
    try {
      if (fileExists(configFile)) {
        jsonContent = fileRead(configFile);
        return deserializeJSON(jsonContent);
      } else {
        // Create default config if doesn't exist
        defaultConfig = getDefaultConfig();
        saveConfig(defaultConfig, "system", "Initial configuration");
        return defaultConfig;
      }
    } catch (any e) {
      return {error: e.message};
    }
  }
  Â
  // Save configuration to file
  function saveConfig(config, updatedBy, changeNote) {
    try {
      // Update metadata
      config.lastUpdated = dateTimeFormat(now(), "yyyy-mm-dd HH:nn:ss");
      config.updatedBy = updatedBy;
      Â
      // Create backup of current config
      if (fileExists(configFile)) {
        backupFile = backupDir & "app_settings_" & dateFormat(now(), "yyyymmdd_HHnnss") & ".json";
        fileCopy(configFile, backupFile);
      }
      Â
      // Serialize and save
      jsonContent = serializeJSON(config);
      fileWrite(configFile, jsonContent);
      Â
      return {success: true, message: "Configuration saved successfully"};
    } catch (any e) {
      return {success: false, error: e.message};
    }
  }
</cfscript>
<h2>Application Configuration Management</h2>
<cfif NOT canAccessConfig>
  <div style="background: ##fff3e0; border: 2px solid ##ff9800; padding: 20px; margin: 20px 0; border-radius: 5px;">
    <h3 style="color: orange; margin: 0;">⚠Configuration Not Available</h3>
    <p>Unable to access configuration directory: <strong>#errorMessage#</strong></p>
    <p>This example demonstrates configuration file management.</p>
  </div>
</cfif>
<!--- Handle form submission --->
<cfif isDefined("form.action") AND form.action EQ "saveConfig" AND canAccessConfig>
  Â
  <cftry>
    <!--- Load current config --->
    <cfset currentConfig = loadConfig()>
    Â
    <!--- Update values from form --->
    <cfset currentConfig.appName = form.appName>
    <cfset currentConfig.branding.primaryColor = form.primaryColor>
    <cfset currentConfig.branding.secondaryColor = form.secondaryColor>
    <cfset currentConfig.features.enableChat = isDefined("form.enableChat")>
    <cfset currentConfig.features.enableNotifications = isDefined("form.enableNotifications")>
    <cfset currentConfig.features.enableAnalytics = isDefined("form.enableAnalytics")>
    <cfset currentConfig.email.fromAddress = form.fromAddress>
    <cfset currentConfig.email.smtpServer = form.smtpServer>
    <cfset currentConfig.email.smtpPort = form.smtpPort>
    Â
    <!--- Save configuration --->
    <cfset saveResult = saveConfig(currentConfig, "admin", "Configuration updated via web interface")>
    Â
    <cfif saveResult.success>
      <div style="background: ##e8f5e9; border: 2px solid ##4caf50; padding: 15px; margin: 20px 0; border-radius: 5px;">
        <strong>✓ Configuration Saved Successfully!</strong>
        <p>A backup of the previous configuration has been created.</p>
      </div>
    <cfelse>
      <div style="background: ##ffebee; border: 2px solid ##f44336; padding: 15px; margin: 20px 0; border-radius: 5px;">
        <strong>✗ Error:</strong> #saveResult.error#
      </div>
    </cfif>
    Â
    <cfcatch type="any">
      <div style="background: ##ffebee; border: 2px solid ##f44336; padding: 15px; margin: 20px 0; border-radius: 5px;">
        <strong>✗ Error:</strong> #cfcatch.message#
      </div>
    </cfcatch>
  </cftry>
  Â
</cfif>
<!--- Load and display current configuration --->
<cfif canAccessConfig>
  <cfset appConfig = loadConfig()>
  Â
  <cfif structKeyExists(appConfig, "error")>
    <div style="background: ##ffebee; border: 2px solid ##f44336; padding: 15px; margin: 15px 0; border-radius: 5px;">
      <strong>✗ Error loading configuration:</strong> #appConfig.error#
    </div>
  <cfelse>
    Â
    <!--- Display current config info --->
    <div style="background: ##e3f2fd; border: 2px solid ##2196f3; padding: 15px; margin: 20px 0; border-radius: 5px;">
      <strong>Configuration File:</strong> <code>app_settings.json</code><br>
      <strong>Last Updated:</strong> #appConfig.lastUpdated#<br>
      <strong>Updated By:</strong> #appConfig.updatedBy#
    </div>
    Â
    <!--- Configuration Edit Form --->
    <h3>Edit Application Settings</h3>
    Â
    <form method="post">
      <input type="hidden" name="action" value="saveConfig">
      Â
      <!--- General Settings --->
      <fieldset style="border: 1px solid ##ccc; padding: 20px; margin: 20px 0; border-radius: 5px;">
        <legend style="font-weight: bold; font-size: 18px;">General Settings</legend>
        Â
        <div style="margin: 15px 0;">
          <label for="appName"><strong>Application Name:</strong></label><br>
          <input type="text" name="appName" id="appName" value="#appConfig.appName#" style="padding: 8px; width: 300px;">
        </div>
        Â
        <div style="margin: 15px 0;">
          <label><strong>Version:</strong></label><br>
          <input type="text" value="#appConfig.version#" disabled style="padding: 8px; width: 150px; background: ##f5f5f5;">
        </div>
      </fieldset>
      Â
      <!--- Branding Settings --->
      <fieldset style="border: 1px solid ##ccc; padding: 20px; margin: 20px 0; border-radius: 5px;">
        <legend style="font-weight: bold; font-size: 18px;">Branding</legend>
        Â
        <div style="margin: 15px 0;">
          <label for="primaryColor"><strong>Primary Color:</strong></label><br>
          <input type="color" name="primaryColor" id="primaryColor" value="#appConfig.branding.primaryColor#" style="padding: 5px; width: 100px; height: 40px;">
          <input type="text" value="#appConfig.branding.primaryColor#" readonly style="padding: 8px; width: 100px; margin-left: 10px;">
        </div>
        Â
        <div style="margin: 15px 0;">
          <label for="secondaryColor"><strong>Secondary Color:</strong></label><br>
          <input type="color" name="secondaryColor" id="secondaryColor" value="#appConfig.branding.secondaryColor#" style="padding: 5px; width: 100px; height: 40px;">
          <input type="text" value="#appConfig.branding.secondaryColor#" readonly style="padding: 8px; width: 100px; margin-left: 10px;">
        </div>
      </fieldset>
      Â
      <!--- Feature Flags --->
      <fieldset style="border: 1px solid ##ccc; padding: 20px; margin: 20px 0; border-radius: 5px;">
        <legend style="font-weight: bold; font-size: 18px;">Feature Flags</legend>
        Â
        <div style="margin: 15px 0;">
          <label>
            <input type="checkbox" name="enableChat" #appConfig.features.enableChat ? "checked" : ""#>
            <strong>Enable Live Chat</strong>
          </label>
        </div>
        Â
        <div style="margin: 15px 0;">
          <label>
            <input type="checkbox" name="enableNotifications" #appConfig.features.enableNotifications ? "checked" : ""#>
            <strong>Enable Notifications</strong>
          </label>
        </div>
        Â
        <div style="margin: 15px 0;">
          <label>
            <input type="checkbox" name="enableAnalytics" #appConfig.features.enableAnalytics ? "checked" : ""#>
            <strong>Enable Analytics Tracking</strong>
          </label>
        </div>
      </fieldset>
      Â
      <!--- Email Settings --->
      <fieldset style="border: 1px solid ##ccc; padding: 20px; margin: 20px 0; border-radius: 5px;">
        <legend style="font-weight: bold; font-size: 18px;">Email Configuration</legend>
        Â
        <div style="margin: 15px 0;">
          <label for="fromAddress"><strong>From Address:</strong></label><br>
          <input type="email" name="fromAddress" id="fromAddress" value="#appConfig.email.fromAddress#" style="padding: 8px; width: 300px;">
        </div>
        Â
        <div style="margin: 15px 0;">
          <label for="smtpServer"><strong>SMTP Server:</strong></label><br>
          <input type="text" name="smtpServer" id="smtpServer" value="#appConfig.email.smtpServer#" style="padding: 8px; width: 300px;">
        </div>
        Â
        <div style="margin: 15px 0;">
          <label for="smtpPort"><strong>SMTP Port:</strong></label><br>
          <input type="number" name="smtpPort" id="smtpPort" value="#appConfig.email.smtpPort#" style="padding: 8px; width: 150px;">
        </div>
      </fieldset>
      Â
      <!--- Submit Button --->
      <div style="margin: 20px 0;">
        <button type="submit" style="padding: 12px 30px; background: ##4caf50; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 16px;">
          💾 Save Configuration
        </button>
      </div>
    </form>
    Â
    <!--- View Raw JSON --->
    <h3>Raw Configuration (JSON)</h3>
    <div style="background: ##263238; color: ##aed581; padding: 20px; border-radius: 5px; overflow-x: auto; font-family: 'Courier New', monospace; font-size: 14px;">
      <pre style="margin: 0;"><cfoutput>#serializeJSON(appConfig)#</cfoutput></pre>
    </div>
    Â
  </cfif>
</cfif>
<!--- List Configuration Backups --->
<cfif canAccessConfig>
  <h3>Configuration Backups</h3>
  Â
  <cftry>
    <cfset backupFiles = directoryList(backupDir, false, "query", "*.json", "dateLastModified desc")>
    Â
    <cfif backupFiles.recordCount GT 0>
      <table style="width: 100%; border-collapse: collapse; margin: 15px 0;">
        <thead>
          <tr style="background: ##e0e0e0;">
            <th style="padding: 10px; border: 1px solid ##ccc; text-align: left;">Backup File</th>
            <th style="padding: 10px; border: 1px solid ##ccc; text-align: left;">Size</th>
            <th style="padding: 10px; border: 1px solid ##ccc; text-align: left;">Created</th>
          </tr>
        </thead>
        <tbody>
          <cfoutput query="backupFiles" maxrows="10">
            <tr>
              <td style="padding: 10px; border: 1px solid ##ccc;"><code>#name#</code></td>
              <td style="padding: 10px; border: 1px solid ##ccc;">#numberFormat(size / 1024, "0.00")# KB</td>
              <td style="padding: 10px; border: 1px solid ##ccc;">#dateTimeFormat(dateLastModified, "yyyy-mm-dd HH:nn:ss")#</td>
            </tr>
          </cfoutput>
        </tbody>
      </table>
      <cfif backupFiles.recordCount GT 10>
        <p><em>Showing 10 most recent backups. Total: #backupFiles.recordCount#</em></p>
      </cfif>
    <cfelse>
      <p><em>No backup files found.</em></p>
    </cfif>
    Â
    <cfcatch type="any">
      <p><em>Unable to list backup files.</em></p>
    </cfcatch>
  </cftry>
</cfif>
<cfscript>
  // Configuration
  reportsDir = expandPath("./reports/");
  Â
  // Create reports directory if it doesn't exist
  try {
    if (!directoryExists(reportsDir)) {
      directoryCreate(reportsDir);
    }
    canGenerateReports = true;
  } catch (any e) {
    canGenerateReports = false;
    errorMessage = e.message;
  }
  Â
  // Sample sales data (in production, this would come from database)
  function getSalesData() {
    salesData = queryNew("OrderID,CustomerName,Product,Quantity,UnitPrice,TotalAmount,OrderDate",Â
               "integer,varchar,varchar,integer,decimal,decimal,date");
    Â
    // Add sample rows
    queryAddRow(salesData, {
      OrderID: 1001,
      CustomerName: "Acme Corporation",
      Product: "Widget Pro",
      Quantity: 50,
      UnitPrice: 29.99,
      TotalAmount: 1499.50,
      OrderDate: createDate(2024, 10, 15)
    });
    Â
    queryAddRow(salesData, {
      OrderID: 1002,
      CustomerName: "TechStart Inc",
      Product: "Gadget Plus",
      Quantity: 25,
      UnitPrice: 149.99,
      TotalAmount: 3749.75,
      OrderDate: createDate(2024, 10, 18)
    });
    Â
    queryAddRow(salesData, {
      OrderID: 1003,
      CustomerName: "Global Services Ltd",
      Product: "Widget Pro",
      Quantity: 100,
      UnitPrice: 29.99,
      TotalAmount: 2999.00,
      OrderDate: createDate(2024, 10, 20)
    });
    Â
    queryAddRow(salesData, {
      OrderID: 1004,
      CustomerName: "Digital Solutions",
      Product: "SuperTool X",
      Quantity: 15,
      UnitPrice: 299.99,
      TotalAmount: 4499.85,
      OrderDate: createDate(2024, 10, 22)
    });
    Â
    queryAddRow(salesData, {
      OrderID: 1005,
      CustomerName: "Enterprise Co",
      Product: "Gadget Plus",
      Quantity: 75,
      UnitPrice: 149.99,
      TotalAmount: 11249.25,
      OrderDate: createDate(2024, 10, 25)
    });
    Â
    return salesData;
  }
  Â
  // Function to generate CSV content from query
  function generateCSV(data) {
    // Get column names
    columns = data.columnList;
    Â
    // Start with header row
    csvContent = columns & chr(13) & chr(10);
    Â
    // Add data rows
    for (row in data) {
      rowData = [];
      for (col in listToArray(columns)) {
        value = row[col];
        // Escape commas and quotes in data
        if (findNoCase(",", value) OR findNoCase("""", value)) {
          value = """" & replace(value, """", """""", "ALL") & """";
        }
        arrayAppend(rowData, value);
      }
      csvContent &= arrayToList(rowData, ",") & chr(13) & chr(10);
    }
    Â
    return csvContent;
  }
  Â
  // Function to generate formatted text report
  function generateTextReport(data) {
    textContent = "===========================================================================" & chr(13) & chr(10);
    textContent &= "             SALES REPORT                     " & chr(13) & chr(10);
    textContent &= "===========================================================================" & chr(13) & chr(10);
    textContent &= "Generated: " & dateTimeFormat(now(), "yyyy-mm-dd HH:nn:ss") & chr(13) & chr(10);
    textContent &= "Total Orders: " & data.recordCount & chr(13) & chr(10);
    textContent &= "===========================================================================" & chr(13) & chr(10);
    textContent &= chr(13) & chr(10);
    Â
    // Calculate totals
    grandTotal = 0;
    for (row in data) {
      grandTotal += row.TotalAmount;
    }
    Â
    // Add detail rows
    for (row in data) {
      textContent &= "Order ##" & row.OrderID & chr(13) & chr(10);
      textContent &= "  Customer: " & row.CustomerName & chr(13) & chr(10);
      textContent &= "  Product: " & row.Product & chr(13) & chr(10);
      textContent &= "  Quantity: " & row.Quantity & chr(13) & chr(10);
      textContent &= "  Unit Price: " & dollarFormat(row.UnitPrice) & chr(13) & chr(10);
      textContent &= "  Total: " & dollarFormat(row.TotalAmount) & chr(13) & chr(10);
      textContent &= "  Order Date: " & dateFormat(row.OrderDate, "yyyy-mm-dd") & chr(13) & chr(10);
      textContent &= "---------------------------------------------------------------------------" & chr(13) & chr(10);
    }
    Â
    textContent &= chr(13) & chr(10);
    textContent &= "GRAND TOTAL: " & dollarFormat(grandTotal) & chr(13) & chr(10);
    textContent &= "===========================================================================" & chr(13) & chr(10);
    Â
    return textContent;
  }
</cfscript>
<h2>Dynamic Report Generation</h2>
<cfif NOT canGenerateReports>
  <div style="background: ##fff3e0; border: 2px solid ##ff9800; padding: 20px; margin: 20px 0; border-radius: 5px;">
    <h3 style="color: orange; margin: 0;">⚠Report Generation Not Available</h3>
    <p>Unable to access reports directory: <strong>#errorMessage#</strong></p>
    <p>This example demonstrates report generation functionality.</p>
  </div>
</cfif>
<!--- Handle report generation --->
<cfif isDefined("form.action") AND form.action EQ "generate" AND canGenerateReports>
  Â
  <cftry>
    <!--- Get sales data --->
    <cfset salesData = getSalesData()>
    Â
    <!--- Generate report based on format --->
    <cfset reportDate = dateFormat(now(), "yyyy-mm-dd")>
    <cfset reportTime = timeFormat(now(), "HHnnss")>
    Â
    <cfif form.reportFormat EQ "csv">
      <cfset reportContent = generateCSV(salesData)>
      <cfset reportFileName = "sales_report_#reportDate#_#reportTime#.csv">
    <cfelse>
      <cfset reportContent = generateTextReport(salesData)>
      <cfset reportFileName = "sales_report_#reportDate#_#reportTime#.txt">
    </cfif>
    Â
    <cfset reportPath = reportsDir & reportFileName>
    Â
    <!--- Write report to file --->
    <cffile action="write" file="#reportPath#" output="#reportContent#">
    Â
    <!--- Get file info --->
    <cfset reportFileInfo = getFileInfo(reportPath)>
    Â
    <div style="background: ##e8f5e9; border: 2px solid ##4caf50; padding: 20px; margin: 20px 0; border-radius: 5px;">
      <h3 style="color: green; margin: 0;">✓ Report Generated Successfully!</h3>
      <p><strong>Report Name:</strong> #reportFileName#</p>
      <p><strong>Format:</strong> #uCase(form.reportFormat)#</p>
      <p><strong>Records:</strong> #salesData.recordCount#</p>
      <p><strong>File Size:</strong> #numberFormat(reportFileInfo.size / 1024, "0.00")# KB</p>
      <p><strong>Generated:</strong> #dateTimeFormat(reportFileInfo.lastModified, "yyyy-mm-dd HH:nn:ss")#</p>
      Â
      <!--- Download link --->
      <p style="margin-top: 15px;">
        <a href="reports/#reportFileName#" download style="padding: 10px 20px; background: ##2196f3; color: white; text-decoration: none; border-radius: 5px; display: inline-block;">
          📥 Download Report
        </a>
      </p>
    </div>
    Â
    <!--- Preview report content --->
    <h3>Report Preview</h3>
    <div style="background: ##263238; color: ##aed581; padding: 20px; border-radius: 5px; overflow-x: auto; font-family: 'Courier New', monospace; font-size: 14px; max-height: 400px; overflow-y: auto;">
      <pre style="margin: 0; white-space: pre-wrap;"><cfoutput>#htmlEditFormat(reportContent)#</cfoutput></pre>
    </div>
    Â
    <cfcatch type="any">
      <div style="background: ##ffebee; border: 2px solid ##f44336; padding: 15px; margin: 20px 0; border-radius: 5px;">
        <strong>✗ Error generating report:</strong> #cfcatch.message#
      </div>
    </cfcatch>
  </cftry>
  Â
</cfif>
<!--- Report Generation Form --->
<cfif canGenerateReports>
  <div style="background: ##e3f2fd; border: 2px solid ##2196f3; padding: 20px; margin: 20px 0; border-radius: 5px;">
    <h3>Generate Sales Report</h3>
    Â
    <form method="post">
      <input type="hidden" name="action" value="generate">
      Â
      <div style="margin: 15px 0;">
        <label for="reportFormat"><strong>Report Format:</strong></label><br>
        <select name="reportFormat" id="reportFormat" style="padding: 8px; width: 250px;">
          <option value="csv">CSV (Comma-Separated Values)</option>
          <option value="txt">Text (Formatted Report)</option>
        </select>
      </div>
      Â
      <div style="margin: 15px 0;">
        <p><strong>Report Will Include:</strong></p>
        <ul style="margin: 5px 0;">
          <li>Order ID and Customer Name</li>
          <li>Product Details</li>
          <li>Quantity and Pricing</li>
          <li>Order Dates</li>
          <li>Total Calculations</li>
        </ul>
      </div>
      Â
      <div>
        <button type="submit" style="padding: 12px 30px; background: ##4caf50; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 16px;">
          📊 Generate Report
        </button>
      </div>
    </form>
  </div>
</cfif>
<!--- Sample Data Preview --->
<cfif canGenerateReports>
  <h3>Sample Data Preview</h3>
  <cfset sampleData = getSalesData()>
  Â
  <cfdumpÂ
    var="#sampleData#"Â
    label="Sales Data (Sample)"
    expand="yes">
</cfif>
<!--- List Generated Reports --->
<cfif canGenerateReports>
  <h3>Generated Reports</h3>
  Â
  <cftry>
    <cfset reportFiles = directoryList(reportsDir, false, "query", "sales_report_*.*", "dateLastModified desc")>
    Â
    <cfif reportFiles.recordCount GT 0>
      <table style="width: 100%; border-collapse: collapse; margin: 15px 0;">
        <thead>
          <tr style="background: ##e0e0e0;">
            <th style="padding: 10px; border: 1px solid ##ccc; text-align: left;">Report Name</th>
            <th style="padding: 10px; border: 1px solid ##ccc; text-align: left;">Format</th>
            <th style="padding: 10px; border: 1px solid ##ccc; text-align: left;">Size</th>
            <th style="padding: 10px; border: 1px solid ##ccc; text-align: left;">Generated</th>
            <th style="padding: 10px; border: 1px solid ##ccc; text-align: center;">Download</th>
          </tr>
        </thead>
        <tbody>
          <cfoutput query="reportFiles" maxrows="10">
            <tr>
              <td style="padding: 10px; border: 1px solid ##ccc;"><code>#name#</code></td>
              <td style="padding: 10px; border: 1px solid ##ccc;">#uCase(listLast(name, "."))#</td>
              <td style="padding: 10px; border: 1px solid ##ccc;">#numberFormat(size / 1024, "0.00")# KB</td>
              <td style="padding: 10px; border: 1px solid ##ccc;">#dateTimeFormat(dateLastModified, "yyyy-mm-dd HH:nn:ss")#</td>
              <td style="padding: 10px; border: 1px solid ##ccc; text-align: center;">
                <a href="reports/#name#" download style="padding: 5px 15px; background: ##2196f3; color: white; text-decoration: none; border-radius: 3px; display: inline-block;">
                  📥 Download
                </a>
              </td>
            </tr>
          </cfoutput>
        </tbody>
      </table>
      <cfif reportFiles.recordCount GT 10>
        <p><em>Showing 10 most recent reports. Total: #reportFiles.recordCount#</em></p>
      </cfif>
    <cfelse>
      <p><em>No reports generated yet. Generate your first report above.</em></p>
    </cfif>
    Â
    <cfcatch type="any">
      <p><em>Unable to list reports.</em></p>
    </cfcatch>
  </cftry>
</cfif>