How to register Quartz Scheduler with Windsor? - castle-windsor

What I have tried so far?
container.Register(Component.For<Quartz.IScheduler>()
.UsingFactoryMethod(() => GetQuartzScheduler())
.LifeStyle.PerWebRequest);
Inside GetQuartzScheduler()
string tcp = string.Format("tcp://DevMachine:8888/QuartzScheduler");
NameValueCollection properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = string.Format("MyQuartz_{0}", alias);
// set thread pool info
properties["quartz.scheduler.proxy"] = "true";
properties["quartz.threadPool.threadCount"] = "0";
properties["quartz.scheduler.proxy.address"] = tcp; //tcp variable is set before
Quartz.ISchedulerFactory sf = new Quartz.Impl.StdSchedulerFactory(properties);
sched = sf.GetScheduler(); //<--**Throws exception**
The exception is:
Factory method creating instances of component 'Late bound Quartz.IScheduler' returned null. This is not allowed and most likely a bug in the factory method.
Any suggestions to correct this?

Related

How to call stored procedure in Entity Framework Core with input and output parameters using mysql

I am using ASP.net Core 2.2 with Entity Framework core 2.2.6 and Pomelo.EntityFrameworkCore.MySql 2.2.0 for connectivity with MySQL, I have a stored procedure which takes 3 input parameters and 1 output parameter. I am able to call it in MySQL workbench like
CALL GetTechniciansByTrade('Automobile', 1, 10, #total);
select #total;
Now I want to call this using entity framework core, the code I am currently using is
var outputParameter = new MySqlParameter("#PageCount", MySqlDbType.Int32);
outputParameter.Direction = System.Data.ParameterDirection.Output;
var results = await _context.GetTechnicians.FromSql("Call GetTechniciansByTrade(#MyTrade, #PageIndex, #PageSize, #PageCount OUT)",
new MySqlParameter("#MyTrade", Trade),
new MySqlParameter("#PageIndex", PageIndex),
new MySqlParameter("#PageSize", PageSize),
outputParameter).ToListAsync();
int PageCount = (int)outputParameter.Value;
Exception I am getting currently is
Only ParameterDirection.Input is supported when CommandType is Text (parameter name: #PageCount)
Can you try below things.
Use exec instead of call
var results = await _context.GetTechnicians.FromSql("EXEC GetTechniciansByTrade(#MyTrade, #PageIndex, #PageSize, #PageCount OUTPUT)"
Select PageCount in stored procedure
I got information from this github issue.
I found the solution using #matt-g suggestion based on this Question.
I had to use ADO.net for this as
var technicians = new List<TechnicianModel>();
using (MySqlConnection lconn = new MySqlConnection(_context.Database.GetDbConnection().ConnectionString))
{
lconn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = lconn;
cmd.CommandText = "GetTechniciansByTrade"; // The name of the Stored Proc
cmd.CommandType = CommandType.StoredProcedure; // It is a Stored Proc
cmd.Parameters.AddWithValue("#Trade", Trade);
cmd.Parameters.AddWithValue("#PageIndex", PageIndex);
cmd.Parameters.AddWithValue("#PageSize", PageSize);
cmd.Parameters.AddWithValue("#PageCount", MySqlDbType.Int32);
cmd.Parameters["#PageCount"].Direction = ParameterDirection.Output; // from System.Data
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
technicians.Add(new TechnicianModel()
{
City = reader["City"].ToString(),
ExperienceYears = reader["ExperienceYears"] != null ? Convert.ToInt32(reader["ExperienceYears"]) : 0,
Id = Guid.Parse(reader["Id"].ToString()),
Name = reader["Name"].ToString(),
Qualification = reader["Qualification"].ToString(),
Town = reader["Town"].ToString()
});
}
}
Object obj = cmd.Parameters["#PageCount"].Value;
var lParam = (Int32)obj; // more useful datatype
}
}

GCE how to add external IP to existing instance at boot

I'm using Gcloud-java to manage some VM instances. The code to create a new instance is clear and is the following:
Address externalIp = compute.getAddress(addressId);
InstanceId instanceId = InstanceId.of("us-central1-a", "test-instance");
NetworkId networkId = NetworkId.of("default");
PersistentDiskConfiguration attachConfiguration =
PersistentDiskConfiguration.builder(diskId).boot(true).build();
AttachedDisk attachedDisk = AttachedDisk.of("dev0", attachConfiguration);
NetworkInterface networkInterface = NetworkInterface.builder(networkId)
.accessConfigurations(AccessConfig.of(externalIp.address()))
.build();
MachineTypeId machineTypeId = MachineTypeId.of("us-central1-a", "n1-standard-1");
InstanceInfo instance =
InstanceInfo.of(instanceId, machineTypeId, attachedDisk, networkInterface);
Operation operation = compute.create(instance);
// Wait for operation to complete
operation = operation.waitFor();
if (operation.errors() == null) {
System.out.println("Instance " + instanceId + " was successfully created");
} else {
// inspect operation.errors()
throw new RuntimeException("Instance creation failed");
}
But what should I do if I have en existing instance that I want to start and I want to attach an external IP?
I've tried in this way: first I create a RegionAddressId and get an Address with which I create the networkInterface.
RegionAddressId addressId = RegionAddressId.of("europe-west1", "test-address");
Operation operationAdd = compute.create(AddressInfo.of(addressId));
operationAdd = operationAdd.waitFor();
Address externalIp = compute.getAddress(addressId);
NetworkId networkId = NetworkId.of("default");
NetworkInterface networkInterface = NetworkInterface.builder(networkId)
.accessConfigurations(NetworkInterface.AccessConfig.of(externalIp.address()))
.build();
The I get my instance and add the accessConfig
InstanceId instanceId = InstanceId.of("my-server", "europe-west1-b","my-instance");
Instance instance = compute.getInstance(instanceId);
instance.addAccessConfig("default", NetworkInterface.AccessConfig.of(externalIp.address()));
Operation operation = instance.start();
The result is that my instance is booted with another external IP that I don't know how to obtain.
What is the correct procedure?
Thanks
I've found by myself the solution.
Compute compute = ComputeOptions.defaultInstance().service();
InstanceId instanceId = InstanceId.of("my-server", "europe-west1-b","my-instance");
Operation operation = compute.start(instanceId);
Operation completedOperation = operation.waitFor();
if (completedOperation == null) {
// operation no longer exists
} else if (completedOperation.errors() != null) {
// operation failed, handle error
}
Instance instance = compute.getInstance(instanceId);
String publicIp =
instance.networkInterfaces().get(0).accessConfigurations().get(0).natIp();
I start the instance using the start method of Compute and then (after the operation is completed) I get the instance

Crazy exception at AES Decryption - BadPaddingException

I'm having some trouble here while trying to decode some encrypted text.
CheckpswdBasedKey is always returning false, because of the BadPaddingException at c.doFInal
I'm using AES, basicaly the encryption:
public static String generatePswdBasedKey(String password){
String finalKey = null;
SecretKey sk = null;
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, IT, KEY_LENGTH);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
sk = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance(Cifrador.AES_MODE);//AES_MODE = AES/CBC/PKCS5Padding
IvParameterSpec ivParams = new IvParameterSpec(iv);//IV already initialized
cipher.init(Cipher.ENCRYPT_MODE, sk, ivParams);
byte pwdbytes[] = password.getBytes();//I also tried using Base64 to decode... without success
byte cc[] = cipher.doFinal(pwdbytes);
finalKey = Base64.encodeToString(cc, false); //.encodeToString(byte[] sArr, boolean lineSep)
return finalKey;
Now decrypt mode:
//This method compares a password received from keyboard with the decrypted password (decrypting output from generatePswdBasedKey(String password))
public static boolean checkPswdBasedKey(String password, String passwordInput){
byte bufferBytes[] = Base64.decode(password);
SecretKey sk = new SecretKeySpec(bufferBytes, 0, bufferBytes.length, "AES"); //Also tried new SecretKeySPec(bufferBytes, "AES");...
Cipher c = Cipher.getInstance(Cifrador.AES_MODE);//AES_MODE = AES/CBC/PKCS5Padding
IvParameterSpec ivParams = new IvParameterSpec(iv);//IV already initialized
c.init(Cipher.DECRYPT_MODE, sk, ivParams);
byte result[] = c.doFinal(bufferBytes);
String resultStr = Base64.encodeToString(result, false); //.encodeToString(byte[] sArr, boolean lineSep)
if(passwordInput.equalsIgnoreCase(resultStr)){
return true;
}
return false;
}
I compared bytes from iv #checkPswdBasedKey and iv #generatePswdBasedKey and they are all the same. Same happens to the secretkey #checkPswdBasedKey (i get those bytes with: sk.getEncoded() ) and secretkey #generatePswdBasedKey... they are all equal.
So basically when i decrypt i know i'm using the same key, same IV and same message... and an appropiate length (16 bytes key, 16 bytes msg, 16 bytes iv, using AES 128) Any idea?
As Joachim Isaksson commented, if you want to implement a password check, you ought to use a secure hash representation of the password, that is not reversible. This way, the password can't be obtained by decryption even if the hash + key is compromised.
Anyway, in your generatePswdBasedKey you use the PBKDF2WithHmacSHA1 algorithm to generate a SecretKey, and then use that key to encrypt the password. Now you have two options to verify the password in checkPswdBasedKey. Either you:
encrypt the password the same way as in generatePswdBasedKey and compare that they give the same encrypted string
or you
decrypt the encrypted version and compare the result with the password in clear.
I presume that you try the later approach as you init your cipher for decrypt with:
c.init(Cipher.DECRYPT_MODE, sk, ivParams);
Hovewer, for that approach to work you need to instantiate your SecretKey the same way
as you did in generatePswdBasedKey - currently you end up with two different keys.
In generatePswdBasedKey:
SecretKey sk = null;
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, IT, KEY_LENGTH);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
sk = new SecretKeySpec(keyBytes, "AES");
In checkPswdBasedKey:
byte bufferBytes[] = Base64.decode(password);
SecretKey sk = new SecretKeySpec(bufferBytes, 0, bufferBytes.length, "AES");
When that is fixed, you also need to look at your compare logic. You should not do a Base64 encoding of your result before the compare - and the compare ought to be case sensitive.
Don't use:
byte result[] = c.doFinal(bufferBytes);
String resultStr = Base64.encodeToString(result, false);
if (passwordInput.equalsIgnoreCase(resultStr)) {
return true;
}
But instead use:
byte result[] = c.doFinal(bufferBytes);
String resultStr = new String(result);
if (passwordInput.equals(resultStr)) {
return true;
}

not able to call methods after decoding from json

I have a Lua class like below. I am using json to serialize the object and put it in a key value store. I am able to serialize the object and put it in the key value store successfully but i am not able to call any methods of the object after i retrieve the object from the key value store. I understand the json module skips the methods while encoding and my object does not have methods after decoding.
Is there a way to append methods to the class after i decode the object from json to lua ? some thing similar to function pointers in C language.
local class_name = "user_object";
user_object = {}; --user class
function user_object.new (mobile, password, uid)
local self = {};
self.mobile = mobile;
self.uid = uid; -- generate a uid which is a running number.
self.password = password;
self.messages_sent = 0;
self.put_request_count = 0;
self.get_request_count = 0;
self.last_time_active = "";
self.get_tickets = {};
self.put_tickets = {};
self.group_message_stream = {};
self.group_ownerships = {}; -- group names which he is owner of
self.group_memberships = {}; -- group names which he is member of
self.sent_poke_count = 0;
self.sent_poke_stream = {};
self.recv_poke_count = 0;
self.recv_poke_stream = {};
function self:add_put_ticket(ticketid)
table.insert(self.put_tickets, ticketid);
self:incr_put_count();
self:save();
return;
end
function self:add_get_ticket(ticketid)
table.insert(self.get_tickets, ticketid);
self:incr_get_count();
self:save();
return;
end
Function in Lua are first class objects, you can store a function in any variable. The line
function self:add_put_ticket(ticketid)
is equivalent to
self.add_put_ticket = function (self, ticketid)
From there, it should be obvious what to do: define your desired methods where they are accessible and assign them to the appropriate fields after deserialization
You can do this with metatables.
user = { name = 'ponzao' } -- Just a table with values.
User = {} -- Table containing the functions.
function User:allCapsName() return self.name:upper() end -- A method.
setmetatable(user, {__index = User}) -- For unavailable keys all calls are dispatched to User.
print(user:allCapsName()) --> "PONZAO"

SSRS 2008 NULL Parameters

How do you pass in null parameters into a SQL 2008 Report? The code that interfaces with the ReportExecution & ReportService2005 web services always yields an error upon executing the ReportExecutionService.Render() method, after I set the parameters (not including the nullable one) via invoking the ReportExecutionService.SetExecutionParameters() method:
"...This report requires a default or user-defined value for the report parameter...to run or subscribe to this report, you must provide a parameter value."
even though that parameter is defined in the .rdl file as being nullable, and defaulting to null.
Must I change my code? Change parameter options in the .rdl file?
var rs = new ReportExecutionService();
rs.Url= "http://Z/ReportServer/ReportExecution2005.asmx";
rs.Credentials = CredentialCache.DefaultCredentials;
rs.ExecutionHeaderValue = new ExecutionHeader();
var executionInfo = rs.LoadReport(ReportTarget, null);
var parameterList = new List<ParameterValue>();
foreach (ParameterValue parameter in Parameters)
{
parameterList.Add(parameter);
}
foreach (var expectedParameter in executionInfo.Parameters)
{
if
(
expectedParameter.Nullable &&
!parameterList.Exists(delegate(ParameterValue pv)
{ return pv.Name == expectedParameter.Name; })
)
{
var parameter = new ParameterValue();
parameter.Name = expectedParameter.Name;
parameter.Value = null;
parameterList.Add(parameter);
}
}
rs.SetExecutionParameters(parameterList.ToArray(), "en-us");
Warning[] warnings = null;
string[] streamIDs = null;
string encoding = null;
string extension = null;
string mime = null;
var content = rs.Render("PDF", null, out extension, out mime, out encoding, out warnings, out streamIDs);
Seems like a bug in SSRS. Especially since I have some reports where the default null value works, and some giving this error message "...report requires a default or user-defined value for the report parameter..."
Anyway, this code seems to work for me in VB.
params = New ArrayList
...
Dim ssrsPrm As New Microsoft.Reporting.WebForms.ReportParameter(param.Name)
ssrsPrm.Values.Add(Nothing)
params.Add(ssrsPrm)
...
Me.ReportViewer1.ServerReport.SetParameters(DirectCast(params.ToArray(GetType(Microsoft.Reporting.WebForms.ReportParameter)), Microsoft.Reporting.WebForms.ReportParameter()))
Does this answer from a slightly different question help? If not, perhaps more code would be helpful.
HTH