Logfile Class error "You cannot execute this operation since the object has not been created." - smo

We wanted to automate few management operations for new SQL Server installation, so we started looking into
LogFile Class
But this class doesn't let us run the ALTER() method to change log file location. Also doesn't let us add a new file and drop and existing file. Anyone know the internals of this class :) ?
NOTE: I know we can run a SQL query and run ALTER DATABASE MODIFY FILE and copy files and restart db. This question is specific to this class.
I also tried to alter an existing file instead of creating a new one and dropping existing one , and it throws the same error.
ERROR
"{"Drop failed for LogFile 'DBAUtility_log'. "}"
{"You cannot execute this operation since the object has not been created."}
class Program
{
static void Main(string[] args)
{
Server srv = new Server("xx");
Database db = default(Database);
db = srv.Databases["DBAUtility"];
//LogFile LF = new LogFile(srv.Databases.ItemById(0),'DBAUtility_log');
//Console.WriteLine("DB:", srv.Databases.Count());
Console.WriteLine(srv.Name);
Console.WriteLine("DBName" + srv.Databases.ItemById(5).ToString());
LogFile lf = new LogFile();
Console.WriteLine("LF:" + lf.ToString());
lf.Parent = db;
lf.Name = "DBAUtility_NEWLOG";
lf.FileName = "M:\\DBFiles\\SQLlog\\1\\DBAUtility_1.ldf";
lf.Create();
LogFile lf2 = new LogFile();
lf2.Parent = db;
lf2.Name = "DBAUtility_log";
lf2.FileName = "C:\\Install\\DBAUtility_1.ldf";
lf2.Drop(); //ERROR HERE
}
}

Create a log file for this database
$LogFileName = $db.name + '_Log'
$LogFile = New-Object ('Microsoft.SqlServer.Management.SMO.LogFile') ($db, $LogFileName)
$db.LogFiles.Add($LogFile)
$LogFile.FileName = $LogFileName + '.ldf'
$LogFile.Size = $logfilesize * 1024
$LogFile.GrowthType = 'KB'
$LogFile.Growth = $logfilegrowth * 1024
$LogFile.MaxSize = -1
$db.Create()

Related

Saving jTextPane text not working properly

I'm trying to save a "history" I'm building after you sent a command from a line, so every time you press Enter the commands goes to the jTextPane with a line separator... However when I save the file it doesn't seem to get the line separator. Example, my jTextPane has something like:
Create database user
use database user
show tables from database
Instead of saving the workspace just like that, it gives me this:
Create database useruse database usershow tables from database
What should I do? Here's my code
String ar;
String TEXTO = jTextPane1.getText() + System.lineSeparator();
FileFilter ft = new FileNameExtensionFilter("Text Files", ".txt");
FC.setFileFilter(ft);
int returnVal = FC.showSaveDialog(this);
if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
java.io.File saved_file = FC.getSelectedFile();
String file_name = saved_file.toString();
File archivo;
ar = "" + file_name + ".txt";
archivo = new File(ar);
try {
if (saved_file != null) {
try (FileWriter GUARDADO = new FileWriter(ar)) {
GUARDADO.write(TEXTO);
}
}
} catch (IOException exp) {
System.out.println(exp);
}
}
You need to use :
jTextPane1.getDocument().getText(0,jTextPane1.getDocument().getLength());
The issue is that you need to use /n instead of System.lineSeparator. The JTextPane behavior doesn't depends on the System.

Why is my SQLite Database not created/saved to disk?

I created code to create a SQLite database based on the article here.
The most pertinent code is:
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Platypus.db";
private static final String TABLE_VENDORS = "vendors";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_VENDORID = "vendorId";
public static final String COLUMN_COMPANYNAME = "companyName";
public SQLiteHandlerVendors(Context context, String vendor,
SQLiteDatabase.CursorFactory factory, int company) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_VENDORS_TABLE = "CREATE TABLE " +
TABLE_VENDORS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_VENDORID
+ " TEXT," + COLUMN_COMPANYNAME + " TEXT" + ")";
db.execSQL(CREATE_VENDORS_TABLE);
}
public void addVendor(Vendor vendor) {
ContentValues values = new ContentValues();
values.put(COLUMN_VENDORID, vendor.getVendorId());
values.put(COLUMN_COMPANYNAME, vendor.getCompanyName());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_VENDORS, null, values);
db.close();
}
Yet, although the insertions of data seem to be working -- the calls to addVendor() run without any exception being thrown with the following code:
protected void onPostExecute(String result) {
try {
JSONArray jsonArr = new JSONArray(result);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
String vendorId = jsonObj.getString("vendorId");
String companyName = jsonObj.getString("companyName");
Log.i("vendorId", vendorId);
Log.i("companyName", companyName);
// Prepare for writing to db
Vendor vend = new Vendor();
vend.setVendorId(vendorId);
vend.setCompanyName(companyName);
SQLiteHandlerVendors sqliteHandler = new SQLiteHandlerVendors(MainActivity.this, null, null, 1);
sqliteHandler.addVendor(vend);
}
} catch (JSONException j) {
System.out.println(j.getMessage());
Log.i("jsonEx", j.getMessage());
}
Log.i("GetVendorsTask.FromOnPostExecute", result);
}
I cannot locate the Platypus.db file that should have been created.
This article says, "If your application creates a database, this database is by default saved in the directory DATA/data/APP_NAME/databases/FILENAME."
A global search for "Platypus.DB" on my hard drive turns up nothing. Is the database created not being persisted, or is there some other reason why I'm not finding it?
I tried to find it by adding this code:
Log.i("Data Dir", Environment.getDataDirectory().toString());
...and when LogCat gives me is:
04-07 12:36:47.133 1089-1089/platypus.app I/Data Dirīš• /data
There is no "data" folder in C:\Users\clay\AndroidStudioProjects\Platypus, nor is there one in the root of my hard drive (*C:*).
Can the data dir/file only be viewed in some virtual space, in a file system for the emulator or so? If so, how can I actually access the emulator's file system to view this data?
UPDATE
Okay, I opened up this view, and navigated to data/data/hhs (the app's name is really "hhs" not "platypus"):
...but still do not see HHS.DB (I see no "databases" folder below all that)...
UPDATE 2
If I select the "<=" button ("Pull a file from the device") with the file with the size of 16384 highlighted, it does open the "Get Device File" dialog with a filename of "HHS.DB" (just what I was hoping to find).
But, why is its path "data\data\hhs\unnamed folder\unnamed file" instead of "data\data\hhs\databases\HHS.DB"?
The other file (size 8720) is HHS.db-journal
UPDATE 3
After saving those files to my hard drive and downloading SQLite Data Browser, I'm able to verify that the records actually were written to the table:
SQLite Data Browser is a great tool for just such a need!
UPDATE 4
I don't know what changed/how it changed, but it's now working as it should:
There is no "data" folder in
C:\Users\clay\AndroidStudioProjects\Platypus, nor is there one in the
root of my hard drive (C:).
Yes that is corect.
Can the data dir/file only be viewed in some virtual space, in a file
system for the emulator or so? If so, how can I actually access the
emulator's file system to view this data?
Using Eclipse you can pull the db from your emulator
Goto windows open perspective. Goto DDMS
Then goto file explorer-> data->data->see your package name-> databases->Platypus.DB"
/data/data/[packagename]/databases/
You select the db and there is a option to pull the db and then you can use a sqlite browser to view the data

DB2DataAdapter.Fill(dataset) throws error "SQL0901N (Reason "CPF4273".) SQLSTATE=58004"

My application is Dot Net based.I am using VS My application uses IBm DB2 at its backend.
My Query is
SELECT A, B FROM SERVER.D WHERE A IN
(SELECT C FROM SERVER.E WHERE X = '01OBPP' AND Y= 'U' AND Z= '1')
A,B,C,X,Y,Z-COLUMN NAME, SERVER- SERVER NAME, D AND E -TABLE NAME
PFB the code-
DB2DataAdapter dbAdapter = null;
DB2Connection dbConn = null;
DB2Command dbCommand;
DataSet dsReturnDataSet ;
dbConn = new DB2Connection(connectionString);
if (dbConn.State == ConnectionState.Closed) dbConn.Open();
dsReturnDataSet.Clear();
dbCommand = GetCommand();
dbCommand.CommandText = queryString;
dbCommand.Connection = dbConn;
dbAdapter = new DB2DataAdapter((DB2Command)dbCommand);
dbAdapter.Fill(dsReturnDataSet);
return dsReturnDataSet;
The GetCommand() method has the following statement
DB2Command dbCommand;
dbCommand = null;
dbCommand = new DB2Command();
dbCommand.CommandType = CommandType.Text;
dbCommand.CommandTimeout = 30;
return dbCommand;
While it hits the line 'dbAdapter.Fill(dsReturnDataSet);' it stucks there for a very long time and after that it throws the error
"ERROR [58004] [IBM][AS] SQL0901N The SQL statement failed because of
a non-severe system error. Subsequent SQL statements can be processed.
(Reason "CPF4273".) SQLSTATE=58004"
Please provide some pointers.
i will be very grateful if any one can give some pointers as to hoW to solve this error.
Check your database log. There should be a db2diag.log file in the db2dump directory under the instance's sqllib directory. Search this file for the above error and it should contain the root cause (that non-severe system error) that it refers to.

Log Fiddler Requests to Database Real-time

Is there any way to log all requests ongoing to a database or can you only log snapshots to a database?
The following example relies upon OLEDB 4.0 which is not available for 64bit processes. You can either select another data provider (e.g. SQLServer) or you can force Fiddler to run in 32bit mode.
Add the following to the Rules file to create a new menu item.
// Log the currently selected sessions in the list to a database.
// Note: The DB must already exist and you must have permissions to write to it.
public static ToolsAction("Log Selected Sessions")
function DoLogSessions(oSessions: Fiddler.Session[]){
if (null == oSessions || oSessions.Length < 1){
MessageBox.Show("Please select some sessions first!");
return;
}
var strMDB = "C:\\log.mdb";
var cnn = null;
var sdr = null;
var cmd = null;
try
{
cnn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strMDB);
cnn.Open();
cmd = new OleDbCommand();
cmd.Connection = cnn;
for (var x = 0; x < oSessions.Length; x++){
var strSQL = "INSERT into tblSessions ([ResponseCode],[URL]) Values (" +
oSessions[x].responseCode + ", '" + oSessions[x].url + "')";
cmd.CommandText = strSQL;
cmd.ExecuteNonQuery();
}
}
catch (ex){
MessageBox.Show(ex);
}
finally
{
if (cnn != null ){
cnn.Close();
}
}
}
Note: To use the Database Objects in Fiddler 2.3.9 and below, you'll need to add system.data to the References list inside Tools | Fiddler Options | Extensions | Scripting. In 2.3.9.1 and later, this reference will occur automatically.
Then, list the new import at the top of your rules script:
import System.Data.OleDb;
see FiddlerScript CookBook

Zend move_uploaded_file Failure

I have spent a couple hours trying to add a simple upload file option to my Zend application. I have double checked all of the necessary permissions and everything works fine. Quite simply, I have it uploading nicely to a temporary folder but once I have it in that temp folder, I can't get it to move to its permanent storage location. Below is the code that keeps failing...
To be precise, the code fails with the $uploaded die statement. I thought it might be an issue since I am sending it to the Model rather than handling it right in the Action but that didn't solve the problem either. Can anyone point me in the right direction? I just can't get the file out of the temprorary directly and into the permenant storage locatoin I want.
Thank you!
//This is the action that is called when form is submitted.
function addImageAction()
{
$imgForm = new Admin_Form_ImageUploadForm();
$imgForm->setAction('/admin/media/add-image');
$imgForm->setMethod('post');
$this->view->form = $imgForm;
if($this->getRequest()->isPost())
{
if(!$imgForm->image->receive())
{
$this->view->message = '<div class="popup-warning">Errors Receiving File.</div>';
$this->_redirect('/admin/media/add-image');
}
if($imgForm->image->isUploaded())
{
$imageModel = new Admin_Model_Image();
$imageId = $imageModel->addImage($imgForm->image->getFileName());
$this->_redirect('/admin/media/view-image/'.$imageId);
}
}
}
Block #2 - The Model
public function addImage($image)
{
// Process the New File
// Check to see if Filename is already in Database
$select = $this->select();
$select->where('filename=?', $image);
$row = $this->fetchRow($select);
if ($row)
{
die("Filename already exists in Database. Please try another file.");
}
// Move file to Storage Directory
// Check/Create Storage Directoy (YYYYMMDD)
// Temporarily set MEDIA_DIR
$mediaDir = APPLICATION_PATH . '/../public/media/uploads/';
$destinationDir = $mediaDir . date('Ymd');
if (!is_dir($destinationDir)){
$storageDir = mkdir($destinationDir);
}
// Save Image
$uploaded = is_uploaded_file($image);
if (!$uploaded) {
die("Image has not been uploaded");
}
$image_saved = move_uploaded_file($image, $destinationDir);
if(!$image_saved)
{
die("Image could not be moved");
}
// Create Alternative Sizes
// Save Data to Database Tables
$dateObject = new Zend_Date();
$row = $this->createRow();
$row->filename = $image;
$row->date_added = $dateObject->get(Zend_Date::TIMESTAMP);
$row->date_modified = $dateObject->get(Zend_Date::TIMESTAMP);
$row->save();
// Fetch the ID of the newly created row
$id = $this->_db->lastInsertId();
// Retrieve IPTC Data
// Retrieve EXIF Data
// Return Image ID
return $id;
}
receive() method moves the file using move_uploaded_file(). So the file you work with is not uploaded anymore, it's normal file. You should use standard copy() function instead.