How to backup and restore sessions on Fiddler startup and shutdown? - automation

What I want is backup all sessions at Fiddler shutdown and when I turn it on again it needs to load that sessions again.
I managed to change the FiddlerScript by creating a save action and dump all sessions with this:
case "save":
FiddlerObject.UI.actSelectAll();
FiddlerObject.UI.actSaveSessionsToZip(CONFIG.GetPath("Captures") + "saved.saz");
FiddlerObject.StatusText = "Saved in " + CONFIG.GetPath("Captures") + "saved.saz";
break;
It works fine and all currently loaded sessions are saved.
I tried to create a action to restore them but it does nothing (I loaded the session but don't know how to get back in the grid):
case "restore":
//I don't know what I need to do with this
Utilities.ReadSessionArchive(CONFIG.GetPath("Captures") + "saved.saz", true);
break;
After that I want to do something similar do execute them with ExecAction at startup and shutdown but this is another part of my puzzle.
TL;DR
How to restore a previously saved dump using FiddlerScript on startup?

Rules > Customize Rules.
Update the OnBoot and OnShutdown functions thusly:
static function OnBoot() {
FiddlerApplication.UI.actLoadSessionArchive("_stored.saz");
}
static function OnShutdown() {
FiddlerApplication.UI.actSelectAll();
var sFilename = (CONFIG.GetPath("Captures") + "_stored.saz");
FiddlerApplication.UI.actSaveSessionsToZip(sFilename);
}

Related

Redis StackExchange LuaScripts with parameters

I'm trying to use the following Lua script using C# StackExchange library:
private const string LuaScriptToExecute = #"
local current
current = redis.call(""incr"", KEYS[1])
if current == 1 then
redis.call(""expire"", KEYS[1], KEYS[2])
return 1
else
return current
end
Whenever i'm evaluating the script "as a string", it works properly:
var incrementValue = await Database.ScriptEvaluateAsync(LuaScriptToExecute,
new RedisKey[] { key, ttlInSeconds });
If I understand correctly, each time I invoke the ScriptEvaluateAsync method, the script is transmitted to the redis server which is not very effective.
To overcome this, I tried using the "prepared script" approach, by running:
_setCounterWithExpiryScript = LuaScript.Prepare(LuaScriptToExecute);
...
...
var incrementValue = await Database.ScriptEvaluateAsync(_setCounterWithExpiryScript,
new[] { key, ttlInSeconds });
Whenever I try to use this approach, I receive the following error:
ERR Error running script (call to f_7c891a96328dfc3aca83aa6fb9340674b54c4442): #user_script:3: #user_script: 3: Lua redis() command arguments must be strings or integers
What am I doing wrong?
What is the right approach in using "prepared" LuaScripts that receive dynamic parameters?
If I look in the documentation: no idea.
If I look in the unit test on github it looks really easy.
(by the way, is your ttlInSeconds really RedisKey and not RedisValue? You are accessing it thru KEYS[2] - shouldnt that be ARGV[1]? Anyway...)
It looks like you should rewrite your script to use named parameters and not arguments:
private const string LuaScriptToExecute = #"
local current
current = redis.call(""incr"", #myKey)
if current == 1 then
redis.call(""expire"", #myKey, #ttl)
return 1
else
return current
end";
// We should load scripts to whole redis cluster. Even when we dont have any.
// In that case, there will be only one EndPoint, one iteration etc...
_myScripts = _redisMultiplexer.GetEndPoints()
.Select(endpoint => _redisMultiplexer.GetServer(endpoint))
.Where(server => server != null)
.Select(server => lua.Load(server))
.ToArray();
Then just execute it with anonymous class as parameter:
for(var setCounterWithExpiryScript in _myScripts)
{
var incrementValue = await Database.ScriptEvaluateAsync(
setCounterWithExpiryScript,
new {
myKey: (RedisKey)key, // or new RedisKey(key) or idk
ttl: (RedisKey)ttlInSeconds
}
)// .ConfigureAwait(false); // ? ;-)
// when ttlInSeconds is value and not key, just dont cast it to RedisKey
/*
var incrementValue = await
Database.ScriptEvaluateAsync(
setCounterWithExpiryScript,
new {
myKey: (RedisKey)key,
ttl: ttlInSeconds
}
).ConfigureAwait(false);*/
}
Warning:
Please note that Redis is in full-stop mode when executing scripts. Your script looks super-easy (you sometimes save one trip to redis (when current != 1) so i have a feeling that this script will be counter productive in greater-then-trivial scale. Just do one or two calls from c# and dont bother with this script.
First of all, Jan's comment above is correct.
The script line that updated the key's TTL should be redis.call(""expire"", KEYS[1], ARGV[1]).
Regarding the issue itself, after searching for similar issues in RedisStackExchange's Github, I found that Lua scripts do not work really well in cluster mode.
Fortunately, it seems that "loading the scripts" isn't really necessary.
The ScriptEvaluateAsync method works properly in cluster mode and is sufficient (caching-wise).
More details can be found in the following Github issue.
So at the end, using ScriptEvaluateAsync without "preparing the script" did the job.
As a side note about Jan's comment above that this script isn't needed and can be replaced with two C# calls, it is actually quite important since this operation should be atomic as it is a "Rate limiter" pattern.

Converting a doc to a pdf in a mvc c# environment

Hi I've got a c# MVC application running under a particular user (app.pool user).
I need to convert a doc or docx file to a pdf.
I thought a good option would be to use libreoffice to fire a process that would start this.
To make life easier for myself (and if libreoffice shouldn't work) I used a batch file.
echo on
SET var1=%2
IF "%var1:~-1%"=="\" SET var1=%var1:~0,-1%
cd %var1%
echo %1
echo %var1%
start /wait "" "C:\Program Files (x86)\LibreOffice 4\program\soffice" -headless -convert-to pdf %1 -outdir %var1%
My code for starting this is as follows.
var ba = #"C:\inetpub\wwwroot\apps\xxxxxxxxx\Services\convert.bat";
fullPath = #"C:\inetpub\wwwroot\apps\xxxxxxxxx\Files\Temp\636295920370843147.doc";
var tempPath = #"C:\inetpub\wwwroot\apps\xxxxxxxxx\Files\Temp";
string command = ba;
//Process.Start(command, fullPath + " " + tempPath);
var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command + " "+ fullPath+ " "+ tempPath);
processInfo.CreateNoWindow = false;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
var process = Process.Start(processInfo);
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
Trace.WriteLine("output>>" + e.Data);
process.BeginOutputReadLine();
process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
Trace.WriteLine("error>>" + e.Data);
process.BeginErrorReadLine();
process.WaitForExit();
Trace.WriteLine("ExitCode: {0}", process.ExitCode.ToString());
process.Close();
This does seem to work manually but when I run the code I can see the whole thing just stalls around the conversion. Looking at the threads and it seems to load the gdiplus.dll which I think is a graphics module which doesn't seem right.
The process though when I copy and paste that into my 'run' box in windows works fine and the pdf is made.
I've checked that the app.pool user has access to both libreoffice and also the folder with the files.
I've ran this as the app.pool user, in the c# it just stalls on the process.WaitForExit();
line. Until I kill the process.
Any ideas?
I've also tried many different ways of executing the soffice conversion. just straight from the c# - libreoffice 4,5.
I've seen some people use libreoffice as a service, is this an option? If so how?
Richard
EDIT
Ah, just changed the app Pool user to myself and now it works, so there is a permissions thing with the standard app pool user. How to find out what....
I added the user into the administrators group on the computer and restarted the machine, then it worked.
It might not be the best solution but after 2 days of trying to get this to work I'm not going to argue.
Richard

FW/1 App Calling onApplicationStart on Every Request

I have a FW/1 app on Railo 4.2.2/Apache and for some reason it's calling onApplicationStart on every request. I can tell it's not any reinit code - put in a callStackGet() dump in setupApplication and can see that the root call is onApplicationStart (not via any init hook). Are there any known bugs in Railo that would cause this? I've double checked the application timeout (1 day) and the FW/1 setting - it's turned off - so there should be no reason the app would be losing application scope on every request.
There is another strange thing I'm seeing too, but I don't know that it is related. In setup application I am creating a new user object (via ORM) and persisting it if a local admin doesn't exist. I dump it and see the ID, but it's not in the database when I query the table (yes, I flushed it). The next page hit creates the user again (since it doesn't exist still...).
Edit: Add persist object code for Adam.
function setupApplication() {
// bean factory should look in the model tree for services and beans
var bf = new framework.ioc( "/com/sharp/model" );
setBeanFactory( bf );
ormReload();
if( getEnvironment() == 'dev' ){
writeLog('Checking for dev user');
if( !arrayLen( ormExecuteQuery('from User where username = ?', ['admin']) ) ){
var user = new com.sharp.model.user.User({username: 'admin', password: hash('p#ssw3rd'), isAdmin: true});
entitySave( user );
ormFlush();
writeDump(user);
writeDump(callStackGet());
writeLog('User admin created')
}
else{
var user = bf.getBean('userService').getByUsername('admin');
writeLog('Dev admin user already exists. Done.')
}
var auth = bf.getBean('userService').authenticate( 'admin', 'p#ssw3rd' );
}
}
I think the failure to persist to the DB may be a regression bug with Railo 4.2.2. See https://issues.jboss.org/browse/RAILO-3279
Try wrapping your save/flush in a transaction:
transaction{
entitySave( user );
ormFlush();
}
Normally you shouldn't need both. Either the transaction or ormFlush should make it persist.

Play app failing with no exception thrown

I have a play application running on a linux server. The play application handles an ajax request, the controller code that handles the request :
public static Result getStorageId() {
final String host = request().username();
logger.debug("get storage id from origin:" + host);
Promise<Product> promiseProduct = Akka.future(new Callable<Product>() {
#Override
public Product call() throws Exception {
Partner partner = PartnerModel.getPartner(host);
logger.debug("Partner origin:" + partner.getHost());
** Product productCase = ProductsModel.createProduct();
logger.debug("product created. id:" + productCase.getId());
return productCase;
}
});
return async(promiseProduct
.map(new Function<Product, Result>() {
#Override
public Result apply(Product product) {
return ok();
}
}));
}
The ProductsModel.createProduct() code is
public static Product createProduct(){
logger.debug("creating new product");
Product product = new ProductImpl();
saveProduct(product);
return product;
}
The issue is when an ajax request made the app reaches line ** and stops but there's no error indicated in the application.log file nor in the play console. The debug statement in the first line of createProduct() method is not executed. The app is still running as I can make another ajax request and see the log statement before line **.
I did try "play run" hoping that it might give more info since it runs in debug mode but no luck.
My local development copy works fine. Another thing, I had this issue before and as a desperate attempt I just create a new class "ProductTestModel" with the same functionality as ProductsModel and used it instead of ProductsModel (ie on line ** it goes Product productCase = ProductTestModel.createProduct() ) deployed it and everything worked. Now after several releases I get this problem again.
I'm using GIT to distribute the code to the server and have play compile the app there. Running play clean compile shows no errors.
So what could be the problem?
I found out the root cause of my problem. It's actually a stupid thing, I forgot to include a conf file. Where the code was failing that object was using that conf file.
Talk about hours being wasted!!

WCF - TargetInvocationException was unhandled

I'm trying to create WCF to sync my mobile device with my server. When i try to click sync button it throws TargetInvocationException. Below is the Sync() method.
Code
Cursor.Current = Cursors.WaitCursor;
CustomerProxy.CustomerCacheSyncService svcProxy = new CustomerProxy.CustomerCacheSyncService();
Microsoft.Synchronization.Data.ServerSyncProviderProxy syncProxy =
new Microsoft.Synchronization.Data.ServerSyncProviderProxy(svcProxy);
// Call SyncAgent.Synchronize() to initiate the synchronization process.
// Synchronization only updates the local database, not your project's data source.
CustomerCacheSyncAgent syncAgent = new CustomerCacheSyncAgent();
syncAgent.RemoteProvider = syncProxy;
/*throws error below code*/
Microsoft.Synchronization.Data.SyncStatistics syncStats = syncAgent.Synchronize();
// TODO: Reload your project data source from the local database (for example, call the TableAdapter.Fill method).
customer_ConfirmationTableAdapter.Fill(testHHDataSet.Customer_Confirmation);
// Show synchronization statistics
MessageBox.Show("Changes downloaded: " + syncStats.TotalChangesDownloaded.ToString()
+ "\r\nChanges Uploaded: " + syncStats.TotalChangesUploaded.ToString());
Cursor.Current = Cursors.Default;
Thanks.
I've recreated the Web Service again and it works now. The problem was the mobile device couldnt find my local webservice. Thanks.