Is it possible to replace a system dll with a proxy dll? - windows

After reading this interesting article:
http://www.codeproject.com/Articles/16541/Create-your-Proxy-DLLs-automatically
I've decided to try and create a proxy dll for pure research purposes. :-)
I did all the steps on ws2_32.dll and this is the code I've got:
#include <windows.h>
#include <stdio.h>
#pragma pack(1)
HINSTANCE hLThis = 0;
HINSTANCE hL = 0;
FARPROC p[182] = {0};
BOOL WINAPI DllMain(HINSTANCE hInst,DWORD reason,LPVOID)
{
//to get indication whether we were loaded
FILE* f;
fopen_s(&f, "C:\\load.txt", "a+");
fclose(f);
if (reason == DLL_PROCESS_ATTACH)
{
hLThis = hInst;
hL = LoadLibrary("ws2_32_.dll");
if (!hL) return false;
p[0] = GetProcAddress(hL,"FreeAddrInfoEx");
p[1] = GetProcAddress(hL,"FreeAddrInfoExW");
p[2] = GetProcAddress(hL,"FreeAddrInfoW");
p[3] = GetProcAddress(hL,"GetAddrInfoExA");
p[4] = GetProcAddress(hL,"GetAddrInfoExW");
p[5] = GetProcAddress(hL,"GetAddrInfoW");
p[6] = GetProcAddress(hL,"GetNameInfoW");
p[7] = GetProcAddress(hL,"InetNtopW");
p[8] = GetProcAddress(hL,"InetPtonW");
p[9] = GetProcAddress(hL,"SetAddrInfoExA");
p[10] = GetProcAddress(hL,"SetAddrInfoExW");
p[11] = GetProcAddress(hL,"WEP");
p[12] = GetProcAddress(hL,"WPUCompleteOverlappedRequest");
p[13] = GetProcAddress(hL,"WSAAccept");
p[14] = GetProcAddress(hL,"WSAAddressToStringA");
p[15] = GetProcAddress(hL,"WSAAddressToStringW");
p[16] = GetProcAddress(hL,"WSAAdvertiseProvider");
p[17] = GetProcAddress(hL,"WSAAsyncGetHostByAddr");
p[18] = GetProcAddress(hL,"WSAAsyncGetHostByName");
p[19] = GetProcAddress(hL,"WSAAsyncGetProtoByName");
p[20] = GetProcAddress(hL,"WSAAsyncGetProtoByNumber");
p[21] = GetProcAddress(hL,"WSAAsyncGetServByName");
p[22] = GetProcAddress(hL,"WSAAsyncGetServByPort");
p[23] = GetProcAddress(hL,"WSAAsyncSelect");
p[24] = GetProcAddress(hL,"WSACancelAsyncRequest");
p[25] = GetProcAddress(hL,"WSACancelBlockingCall");
p[26] = GetProcAddress(hL,"WSACleanup");
p[27] = GetProcAddress(hL,"WSACloseEvent");
p[28] = GetProcAddress(hL,"WSAConnect");
p[29] = GetProcAddress(hL,"WSAConnectByList");
p[30] = GetProcAddress(hL,"WSAConnectByNameA");
p[31] = GetProcAddress(hL,"WSAConnectByNameW");
p[32] = GetProcAddress(hL,"WSACreateEvent");
p[33] = GetProcAddress(hL,"WSADuplicateSocketA");
p[34] = GetProcAddress(hL,"WSADuplicateSocketW");
p[35] = GetProcAddress(hL,"WSAEnumNameSpaceProvidersA");
p[36] = GetProcAddress(hL,"WSAEnumNameSpaceProvidersExA");
p[37] = GetProcAddress(hL,"WSAEnumNameSpaceProvidersExW");
p[38] = GetProcAddress(hL,"WSAEnumNameSpaceProvidersW");
p[39] = GetProcAddress(hL,"WSAEnumNetworkEvents");
p[40] = GetProcAddress(hL,"WSAEnumProtocolsA");
p[41] = GetProcAddress(hL,"WSAEnumProtocolsW");
p[42] = GetProcAddress(hL,"WSAEventSelect");
p[43] = GetProcAddress(hL,"WSAGetLastError");
p[44] = GetProcAddress(hL,"WSAGetOverlappedResult");
p[45] = GetProcAddress(hL,"WSAGetQOSByName");
p[46] = GetProcAddress(hL,"WSAGetServiceClassInfoA");
p[47] = GetProcAddress(hL,"WSAGetServiceClassInfoW");
p[48] = GetProcAddress(hL,"WSAGetServiceClassNameByClassIdA");
p[49] = GetProcAddress(hL,"WSAGetServiceClassNameByClassIdW");
p[50] = GetProcAddress(hL,"WSAHtonl");
p[51] = GetProcAddress(hL,"WSAHtons");
p[52] = GetProcAddress(hL,"WSAInstallServiceClassA");
p[53] = GetProcAddress(hL,"WSAInstallServiceClassW");
p[54] = GetProcAddress(hL,"WSAIoctl");
p[55] = GetProcAddress(hL,"WSAIsBlocking");
p[56] = GetProcAddress(hL,"WSAJoinLeaf");
p[57] = GetProcAddress(hL,"WSALookupServiceBeginA");
p[58] = GetProcAddress(hL,"WSALookupServiceBeginW");
p[59] = GetProcAddress(hL,"WSALookupServiceEnd");
p[60] = GetProcAddress(hL,"WSALookupServiceNextA");
p[61] = GetProcAddress(hL,"WSALookupServiceNextW");
p[62] = GetProcAddress(hL,"WSANSPIoctl");
p[63] = GetProcAddress(hL,"WSANtohl");
p[64] = GetProcAddress(hL,"WSANtohs");
p[65] = GetProcAddress(hL,"WSAPoll");
p[66] = GetProcAddress(hL,"WSAProviderCompleteAsyncCall");
p[67] = GetProcAddress(hL,"WSAProviderConfigChange");
p[68] = GetProcAddress(hL,"WSARecv");
p[69] = GetProcAddress(hL,"WSARecvDisconnect");
p[70] = GetProcAddress(hL,"WSARecvFrom");
p[71] = GetProcAddress(hL,"WSARemoveServiceClass");
p[72] = GetProcAddress(hL,"WSAResetEvent");
p[73] = GetProcAddress(hL,"WSASend");
p[74] = GetProcAddress(hL,"WSASendDisconnect");
p[75] = GetProcAddress(hL,"WSASendMsg");
p[76] = GetProcAddress(hL,"WSASendTo");
p[77] = GetProcAddress(hL,"WSASetBlockingHook");
p[78] = GetProcAddress(hL,"WSASetEvent");
p[79] = GetProcAddress(hL,"WSASetLastError");
p[80] = GetProcAddress(hL,"WSASetServiceA");
p[81] = GetProcAddress(hL,"WSASetServiceW");
p[82] = GetProcAddress(hL,"WSASocketA");
p[83] = GetProcAddress(hL,"WSASocketW");
p[84] = GetProcAddress(hL,"WSAStartup");
p[85] = GetProcAddress(hL,"WSAStringToAddressA");
p[86] = GetProcAddress(hL,"WSAStringToAddressW");
p[87] = GetProcAddress(hL,"WSAUnadvertiseProvider");
p[88] = GetProcAddress(hL,"WSAUnhookBlockingHook");
p[89] = GetProcAddress(hL,"WSAWaitForMultipleEvents");
p[90] = GetProcAddress(hL,"WSApSetPostRoutine");
p[91] = GetProcAddress(hL,"WSCDeinstallProvider");
p[92] = GetProcAddress(hL,"WSCDeinstallProvider32");
p[93] = GetProcAddress(hL,"WSCEnableNSProvider");
p[94] = GetProcAddress(hL,"WSCEnableNSProvider32");
p[95] = GetProcAddress(hL,"WSCEnumNameSpaceProviders32");
p[96] = GetProcAddress(hL,"WSCEnumNameSpaceProvidersEx32");
p[97] = GetProcAddress(hL,"WSCEnumProtocols");
p[98] = GetProcAddress(hL,"WSCEnumProtocols32");
p[99] = GetProcAddress(hL,"WSCGetApplicationCategory");
p[100] = GetProcAddress(hL,"WSCGetProviderInfo");
p[101] = GetProcAddress(hL,"WSCGetProviderInfo32");
p[102] = GetProcAddress(hL,"WSCGetProviderPath");
p[103] = GetProcAddress(hL,"WSCGetProviderPath32");
p[104] = GetProcAddress(hL,"WSCInstallNameSpace");
p[105] = GetProcAddress(hL,"WSCInstallNameSpace32");
p[106] = GetProcAddress(hL,"WSCInstallNameSpaceEx");
p[107] = GetProcAddress(hL,"WSCInstallNameSpaceEx32");
p[108] = GetProcAddress(hL,"WSCInstallProvider");
p[109] = GetProcAddress(hL,"WSCInstallProvider64_32");
p[110] = GetProcAddress(hL,"WSCInstallProviderAndChains64_32");
p[111] = GetProcAddress(hL,"WSCSetApplicationCategory");
p[112] = GetProcAddress(hL,"WSCSetProviderInfo");
p[113] = GetProcAddress(hL,"WSCSetProviderInfo32");
p[114] = GetProcAddress(hL,"WSCUnInstallNameSpace");
p[115] = GetProcAddress(hL,"WSCUnInstallNameSpace32");
p[116] = GetProcAddress(hL,"WSCUpdateProvider");
p[117] = GetProcAddress(hL,"WSCUpdateProvider32");
p[118] = GetProcAddress(hL,"WSCWriteNameSpaceOrder");
p[119] = GetProcAddress(hL,"WSCWriteNameSpaceOrder32");
p[120] = GetProcAddress(hL,"WSCWriteProviderOrder");
p[121] = GetProcAddress(hL,"WSCWriteProviderOrder32");
p[122] = GetProcAddress(hL,"WahCloseApcHelper");
p[123] = GetProcAddress(hL,"WahCloseHandleHelper");
p[124] = GetProcAddress(hL,"WahCloseNotificationHandleHelper");
p[125] = GetProcAddress(hL,"WahCloseSocketHandle");
p[126] = GetProcAddress(hL,"WahCloseThread");
p[127] = GetProcAddress(hL,"WahCompleteRequest");
p[128] = GetProcAddress(hL,"WahCreateHandleContextTable");
p[129] = GetProcAddress(hL,"WahCreateNotificationHandle");
p[130] = GetProcAddress(hL,"WahCreateSocketHandle");
p[131] = GetProcAddress(hL,"WahDestroyHandleContextTable");
p[132] = GetProcAddress(hL,"WahDisableNonIFSHandleSupport");
p[133] = GetProcAddress(hL,"WahEnableNonIFSHandleSupport");
p[134] = GetProcAddress(hL,"WahEnumerateHandleContexts");
p[135] = GetProcAddress(hL,"WahInsertHandleContext");
p[136] = GetProcAddress(hL,"WahNotifyAllProcesses");
p[137] = GetProcAddress(hL,"WahOpenApcHelper");
p[138] = GetProcAddress(hL,"WahOpenCurrentThread");
p[139] = GetProcAddress(hL,"WahOpenHandleHelper");
p[140] = GetProcAddress(hL,"WahOpenNotificationHandleHelper");
p[141] = GetProcAddress(hL,"WahQueueUserApc");
p[142] = GetProcAddress(hL,"WahReferenceContextByHandle");
p[143] = GetProcAddress(hL,"WahRemoveHandleContext");
p[144] = GetProcAddress(hL,"WahWaitForNotification");
p[145] = GetProcAddress(hL,"WahWriteLSPEvent");
p[146] = GetProcAddress(hL,"__WSAFDIsSet");
p[147] = GetProcAddress(hL,"accept");
p[148] = GetProcAddress(hL,"bind");
p[149] = GetProcAddress(hL,"closesocket");
p[150] = GetProcAddress(hL,"connect");
p[151] = GetProcAddress(hL,"freeaddrinfo");
p[152] = GetProcAddress(hL,"getaddrinfo");
p[153] = GetProcAddress(hL,"gethostbyaddr");
p[154] = GetProcAddress(hL,"gethostbyname");
p[155] = GetProcAddress(hL,"gethostname");
p[156] = GetProcAddress(hL,"getnameinfo");
p[157] = GetProcAddress(hL,"getpeername");
p[158] = GetProcAddress(hL,"getprotobyname");
p[159] = GetProcAddress(hL,"getprotobynumber");
p[160] = GetProcAddress(hL,"getservbyname");
p[161] = GetProcAddress(hL,"getservbyport");
p[162] = GetProcAddress(hL,"getsockname");
p[163] = GetProcAddress(hL,"getsockopt");
p[164] = GetProcAddress(hL,"htonl");
p[165] = GetProcAddress(hL,"htons");
p[166] = GetProcAddress(hL,"inet_addr");
p[167] = GetProcAddress(hL,"inet_ntoa");
p[168] = GetProcAddress(hL,"inet_ntop");
p[169] = GetProcAddress(hL,"inet_pton");
p[170] = GetProcAddress(hL,"ioctlsocket");
p[171] = GetProcAddress(hL,"listen");
p[172] = GetProcAddress(hL,"ntohl");
p[173] = GetProcAddress(hL,"ntohs");
p[174] = GetProcAddress(hL,"recv");
p[175] = GetProcAddress(hL,"recvfrom");
p[176] = GetProcAddress(hL,"select");
p[177] = GetProcAddress(hL,"send");
p[178] = GetProcAddress(hL,"sendto");
p[179] = GetProcAddress(hL,"setsockopt");
p[180] = GetProcAddress(hL,"shutdown");
p[181] = GetProcAddress(hL,"socket");
}
if (reason == DLL_PROCESS_DETACH)
{
FreeLibrary(hL);
}
return 1;
}
// FreeAddrInfoEx
extern "C" __declspec(naked) void __stdcall __E__0__()
{
__asm
{
jmp p[0*4];
}
}
// FreeAddrInfoExW
extern "C" __declspec(naked) void __stdcall __E__1__()
{
__asm
{
jmp p[1*4];
}
}
// FreeAddrInfoW
extern "C" __declspec(naked) void __stdcall __E__2__()
{
__asm
{
jmp p[2*4];
}
}
// GetAddrInfoExA
extern "C" __declspec(naked) void __stdcall __E__3__()
{
__asm
{
jmp p[3*4];
}
}
// GetAddrInfoExW
extern "C" __declspec(naked) void __stdcall __E__4__()
{
__asm
{
jmp p[4*4];
}
}
...
I've compiled it (with the .def file) and got a new proxy.dll file. :-)
So far so good. Now, on my VBox win7 x64 I've renamed the original ws2_32.dll to ws2_32_.dll, placed my proxy.dll in C:\\Windows\\System32\\ and renamed it to ws2_32.dll. I did all of this with live-cd linux because of premmisions problems.
As you can see the proxy loads ws2_32_.dll so we should be okay.
But when the system returns from boot every program uses ws2_32.dll throws an error and the file C:\\load.txt is never create.
I don't know what the guy from the article did to make it work. I've read on google that you need to place (and rename) the proxy.dll in the same directory as the program that you want to run the proxy dll with, but I am looking for a global solution.
Maybe it's a checksum problem? I've read that Microsoft uses some secret checksum on it's system PEs.
Thanks, gfgqtmakia.

Moved to 32bit and now it's working.
Also:
Check your proxy's dependencies, it might need additional .dlls in order to run. (Dependency Walker)
Use this guide to replace the system's .dll. This is faster than rebooting into linux.

Related

how to store the primary key values to the foreign key at same time of save

I am new to the laravel and trying to store the primary key values of patientid to the foreign key of patient_id in address table
$patdet = $request->patdet;
foreach ($patdet as $patdets) {
$pdet = new Patient();
$pdet->fname = $patdets['fname'];
$pdet->mname = $patdets['mname'];
$pdet->lname = $patdets['lname'];
$pdet->age = $patdets['age'];
$pdet->blood_group = $patdets['bloodgroup'];
$pdet->gender = $patdets['gender'];
$ptid = $pdet->save();
}
$addr = $request->address[0];
$address = new Address;
$address->gps_lat = $addr['gps_lat'];
$address->gps_log = $addr['gps_long'];
$address->house_no = $addr['houseno'];
$address->zipcode = $addr['zip_code'];
$address->street = $addr['street'];
$address->chowk = $addr['chowk'];
$address->city = $addr['city'];
$address->patient_id = $patid->id;
$address->save();
I know that $ptid is a local variable and cannot be used in address table, so how can I store it in address table?
Try the following and ask me if it doesn't work
foreach($request->patdet as $key => $patdets)
{
$pdet = new Patient();
$pdet->fname = $patdets['fname'];
$pdet->mname = $patdets['mname'];
$pdet->lname = $patdets['lname'];
$pdet->age = $patdets['age'];
$pdet->blood_group = $patdets['bloodgroup'];
$pdet->gender = $patdets['gender'];
$pdet->save();
$addr = $request->address[$key];
if($pdet->id > 0 && !empty($addr)){
$addrss = new Address;
$addrss->gps_lat = $addr['gps_lat'];
$addrss->gps_log = $addr['gps_long'];
$addrss->house_no = $addr['houseno'];
$addrss->zipcode = $addr['zip_code'];
$addrss->street = $addr['street'];
$addrss->chowk = $addr['chowk'];
$addrss->city = $addr['city'];
$addrss->patient_id = $pdet->id;
$addrss->save();
}
}
Try the following
$patArray = $request->patdet;
$addressArray = $request->address;
$pId = array();
foreach($patArray as $key => $patdets){
$pdet = new Patient();
$pdet->fname = $patdets['fname'];
$pdet->mname = $patdets['mname'];
$pdet->lname = $patdets['lname'];
$pdet->age = $patdets['age'];
$pdet->blood_group = $patdets['bloodgroup'];
$pdet->gender = $patdets['gender'];
$pdet->save();
$pId[$key] = ($pdet->id > 0) ? $pdet->id : 0;
}
foreach($addressArray as $key => $addr){
$addrss = new Address;
$addrss->gps_lat = $addr['gps_lat'];
$addrss->gps_log = $addr['gps_long'];
$addrss->house_no = $addr['houseno'];
$addrss->zipcode = $addr['zip_code'];
$addrss->street = $addr['street'];
$addrss->chowk = $addr['chowk'];
$addrss->city = $addr['city'];
$addrss->patient_id = array_key_exists($key ,$pId) ? $pId[$key] : 0;
$addrss->save();
$i++;
}

How to add new /proc/sys/kernel entries?

I wanted to add the new sysctl parameter in kernel module for the code audit.c and this parameter value should be changed during runtime.Where exactly I need to add the new sysctl code and How to achieve it?
You should use ctl_table in tree hierarchy and handle it in your module.
static struct ctl_table sample_child_table1[] = {
{
.ctl_name = CTL_UNNUMBERED1,
.procname = "sample",
.maxlen = sizeof(int),
.mode = 0444,
.data = &global_var,
.proc_handler = &proc_dointvec_minmax,
.extra1 = &min_val,
.extra2 = &max_val,
},
{}
};
static struct ctl_table sample_parent_table[] = {
{
.ctl_name = CTL_KERN,
.procname = "kernel",
.mode = 0777,
.child = sample_child_table,
{}
},
register_sysctl_table(sample_parent_table)

tarantoolctl connpool.lua:316: attempt to index field 'configuration' (a nil value)

i have error with starting sharding
version of tarantool and os:
main/101/tarantoolctl C> version 1.6.8-654-ge91080f on ubuntu-16.04 LTS
in configuration file
roman#zotac-pc:~$ egrep -v "^[[:space:]]*--|^$" /etc/tarantool/instances.enabled/test.lua
box.cfg {
listen = 3301;
slab_alloc_arena = 0.5;
slab_alloc_minimal = 16;
slab_alloc_maximal = 1048576;
slab_alloc_factor = 1.06;
snapshot_period = 0;
snapshot_count = 6;
panic_on_snap_error = true;
panic_on_wal_error = true;
rows_per_wal = 5000000;
snap_io_rate_limit = nil;
wal_mode = "none";
wal_dir_rescan_delay = 2.0;
io_collect_interval = nil;
readahead = 16320;
log_level = 5;
logger_nonblock = true;
too_long_threshold = 0.5;
}
local function bootstrap()
local space = box.schema.create_space('test')
space:create_index('primary')
box.schema.user.grant('guest', 'read,write,execute', 'universe')
box.schema.user.create('test', { password = 'test' })
box.schema.user.grant('test', 'replication')
box.schema.user.grant('test', 'read,write,execute', 'universe')
end
box.once('test-1.0', bootstrap)
local shard = require('shard')
local shards = {
servers = {
{ uri = [[127.0.0.1:3301]]; zone = [[0]]; };
{ uri = [[127.0.0.1:3302]]; zone = [[1]]; };
};
login = 'test';
password = 'test';
redundancy = 1;
binary = '127.0.0.1:3301';
monitor = false;
}
shard.init(cfg)
roman#zotac-pc:~$
sample error in log file:
main/101/test I> Sharding initialization started...
main/101/test tarantoolctl:422 E> Start failed: /usr/share/tarantool/connpool.lua:316: attempt to index field 'configuration' (a nil value)
main C> entering the event loop
in /etc/tarantool/../example.lua from ubuntu package function shard.init(cfg) need replase shard.init(shards)
below code is working fine:
local shard = require('shard')
local shards = {
servers = {
{ uri = [[127.0.0.1:3301]]; zone = [[0]]; };
{ uri = [[127.0.0.1:3302]]; zone = [[1]]; };
};
login = 'test';
password = 'test';
redundancy = 1;
binary = '127.0.0.1:3301';
monitor = false;
}
shard.init(shards)

How to properly fix contacts in SpriteKit?

I use this code and it has to work, but it doesn't:
static const uint32_t platformCategory = 0x1 << 1;
static const uint32_t playerCategory = 0x1 << 2;
Code of player:
self.player = [SKSpriteNode spriteNodeWithImageNamed:#"player"];
self.player.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.player.size];
self.player.physicsBody.dynamic = false;
self.player.physicsBody.friction = 0;
self.player.physicsBody.usesPreciseCollisionDetection = true;
self.player.physicsBody.categoryBitMask = playerCategory;
self.player.physicsBody.collisionBitMask = platformCategory;
self.player.physicsBody.contactTestBitMask = platformCategory;
[self addChild:self.player];
And code of "platforms":
- (void)addPlatformRight {
int plType = arc4random()%3;
SKSpriteNode * platform = [SKSpriteNode spriteNodeWithImageNamed:[NSString stringWithFormat:#"platform%d", plType]];
platform.position = CGPointMake(self.frame.size.width+100, self.frame.size.height-200);
platform.size = CGSizeMake(platform.size.width*1.2, platform.size.height*2);
platform.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:platform.size];
platform.physicsBody.dynamic = false;
platform.physicsBody.friction = 0;
platform.physicsBody.usesPreciseCollisionDetection = true;
platform.physicsBody.categoryBitMask = platformCategory;
platform.physicsBody.contactTestBitMask = playerCategory;
platform.physicsBody.collisionBitMask = playerCategory;
[self addChild:platform];
[platform runAction:[SKAction sequence:#[[SKAction rotateByAngle:M_PI/4.0*8 duration:3], [SKAction removeFromParent]]]];
}
And
- (void)didBeginContact:(SKPhysicsContact *)contact {
NSLog(#"contact");
}
Unfortunately, this doesn't work. Are there any errors?
two overlapping non-dynamic bodies do not generate contact events, at least one of them has to be dynamic

Subsonic 3.0.0.4 leaking SQL connections?

I've been using Subsonic 3.0.0.4 (ActiveRecord approach) for a while, and I recently coded a small page that basically retrieves about 500 records for a given year, and then i just loop through each of them, creating new instances of the Active Record class, just modifying the Period field, and saving each instance in the loop.
The issue is that after executing that page, a LOT of SQL connections are left hanging/open in SQL server (by looking at the sp_who2). Before the page finishes executing, I get the "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached." error.
The code is the following:
if (string.IsNullOrEmpty(tbPeriodoAGenerar.Text)) return;
var idPeriodo = Convert.ToInt32(tbPeriodoAGenerar.Text);
var nuevaEncuesta = new Encuesta();
nuevaEncuesta.IdPeriodo = idPeriodo;
nuevaEncuesta.IdResponsable = 1;
nuevaEncuesta.fechaCierre1 = Convert.ToDateTime(dpFechaCierre1.Value);
nuevaEncuesta.fechaCierre2 = Convert.ToDateTime(dpFechaCierre2.Value);
nuevaEncuesta.IdTipoEncuesta = (int)ETipoEncuesta.PorAnio;
nuevaEncuesta.nombreEncuesta = NombresEncuestas.COVA;
nuevaEncuesta.nombrePublico = NombresEncuestas.COVA_PUBLICO;
nuevaEncuesta.Save();
var empresasActivas = Empresa.Find(x => x.activo == 1);
foreach (var empresa in empresasActivas)
{
EmpresaEncuesta ee = new EmpresaEncuesta();
ee.IdEmpresa = empresa.IdEmpresa;
ee.IdEncuesta = nuevaEncuesta.IdEncuesta;
ee.IdEstatusContestado = (int)EEstatusEmpresaEncuesta.SinContestar;
ee.fechaMod = DateTime.Now;
ee.IdUsuario = 1;
ee.ipMod = IpUsuarioActual;
ee.Save();
}
if (chkMigrarRespuestas.Checked)
{
var periodosAnteriores = new EncuestaBO().ObtenerPeriodosAnteriores(NombresEncuestas.COVA, idPeriodo);
int? periodoAnterior = null;
if (periodosAnteriores.Tables[0].Rows.Count > 0)
{
periodoAnterior = Convert.ToInt32(periodosAnteriores.Tables[0].Rows[0][Columnas.ID_PERIODO]);
}
if (!periodoAnterior.HasValue) return;
var respuestasCortoPlazo = COVACortoPlazo.Find(x => x.Periodo == (periodoAnterior));
COVACortoPlazo ccp;
foreach (var ccpAnterior in respuestasCortoPlazo)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == ccpAnterior.IdEmpresa).Any()) continue;
ccp = new COVACortoPlazo();
ccp.IdEmpresa = ccpAnterior.IdEmpresa;
ccp.CuentaCortoPlazo = ccpAnterior.CuentaCortoPlazo;
ccp.ComentariosAdicionales = ccpAnterior.ComentariosAdicionales;
ccp.RetiroVoluntarioOpcionId = ccpAnterior.RetiroVoluntarioOpcionId;
ccp.RetiroVoluntarioOtroDesc = ccpAnterior.RetiroVoluntarioOtroDesc;
ccp.RetiroEmpresaOpcionId = ccpAnterior.RetiroEmpresaOpcionId;
ccp.RetiroEmpresaOtroDesc = ccpAnterior.RetiroEmpresaOtroDesc;
ccp.Periodo = idPeriodo;
ccp.Save();
}
var tablaCortoPlazoAnterior = COVATablaCortoPlazo.Find(x => x.Periodo == (periodoAnterior));
COVATablaCortoPlazo ctcp;
foreach (var ctcpAnterior in tablaCortoPlazoAnterior)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == ctcpAnterior.IdEmpresa).Any()) continue;
ctcp = new COVATablaCortoPlazo();
ctcp.IdEmpresa = ctcpAnterior.IdEmpresa;
ctcp.Periodo = idPeriodo;
ctcp.COVASegmentoOpcionId = ctcpAnterior.COVASegmentoOpcionId;
ctcp.NivelDinamicaMin = ctcpAnterior.NivelDinamicaMin;
ctcp.NivelDinamicaMax = ctcpAnterior.NivelDinamicaMax;
ctcp.NombreBono = ctcpAnterior.NombreBono;
ctcp.COVAPeriodicidadOpcionId = ctcpAnterior.COVAPeriodicidadOpcionId;
ctcp.MetodoCalculo = ctcpAnterior.MetodoCalculo;
ctcp.COVABaseCalculoOpcionId = ctcpAnterior.COVABaseCalculoOpcionId;
ctcp.RealAnualizado = ctcpAnterior.RealAnualizado;
ctcp.Save();
}
var respuestasAnual = COVAAnual.Find(x => x.Periodo == (periodoAnterior));
COVAAnual ca;
foreach (var caAnterior in respuestasAnual)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == caAnterior.IdEmpresa).Any()) continue;
ca = new COVAAnual();
ca.IdEmpresa = caAnterior.IdEmpresa;
ca.CuentaAnual = caAnterior.CuentaAnual;
ca.NombreBono = caAnterior.NombreBono;
ca.FechaPago = caAnterior.FechaPago;
ca.ComentariosAdicionales = caAnterior.ComentariosAdicionales;
ca.RetiroVoluntarioOpcionId = caAnterior.RetiroVoluntarioOpcionId;
ca.RetiroVoluntarioOtroDesc = caAnterior.RetiroVoluntarioOtroDesc;
ca.RetiroEmpresaOpcionId = caAnterior.RetiroEmpresaOpcionId;
ca.RetiroEmpresaOtroDesc = caAnterior.RetiroEmpresaOtroDesc;
ca.Periodo = idPeriodo;
ca.Save();
}
var tablaAnualAnterior = COVATablaAnual.Find(x => x.Periodo == (periodoAnterior));
COVATablaAnual cta;
foreach (var ctaAnterior in tablaAnualAnterior)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == ctaAnterior.IdEmpresa).Any()) continue;
cta = new COVATablaAnual();
cta.IdEmpresa = ctaAnterior.IdEmpresa;
cta.Periodo = idPeriodo;
cta.COVASegmentoOpcionId = ctaAnterior.COVASegmentoOpcionId;
cta.NivelDinamicaMin = ctaAnterior.NivelDinamicaMin;
cta.NivelDinamicaMax = ctaAnterior.NivelDinamicaMax;
cta.Minimo = ctaAnterior.Minimo;
cta.Target = ctaAnterior.Target;
cta.Maximo = ctaAnterior.Maximo;
cta.RealAnualPagado = ctaAnterior.RealAnualPagado;
cta.MetodoCalculo = ctaAnterior.MetodoCalculo;
cta.COVABaseCalculoOpcionId = ctaAnterior.COVABaseCalculoOpcionId;
cta.Save();
}
var respuestasLargoPlazo = COVALargoPlazo.Find(x => x.Periodo == (periodoAnterior));
COVALargoPlazo clp;
foreach (var clpAnterior in respuestasLargoPlazo)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == clpAnterior.IdEmpresa).Any()) continue;
clp = new COVALargoPlazo();
clp.IdEmpresa = clpAnterior.IdEmpresa;
clp.CuentaLargoPlazo = clpAnterior.CuentaLargoPlazo;
clp.ComentariosAdicionales = clpAnterior.ComentariosAdicionales;
clp.RetiroVoluntarioOpcionId = clpAnterior.RetiroVoluntarioOpcionId;
clp.RetiroVoluntarioOtroDesc = clpAnterior.RetiroVoluntarioOtroDesc;
clp.RetiroEmpresaOpcionId = clpAnterior.RetiroEmpresaOpcionId;
clp.RetiroEmpresaOtroDesc = clpAnterior.RetiroEmpresaOtroDesc;
clp.PermiteCompraAcciones = clpAnterior.PermiteCompraAcciones;
clp.Periodo = idPeriodo;
clp.Save();
}
var tablaLargoPlazoAnterior = COVATablaLargoPlazo.Find(x => x.Periodo == (periodoAnterior));
COVATablaLargoPlazo ctlp;
foreach (var ctlpAnterior in tablaLargoPlazoAnterior)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == ctlpAnterior.IdEmpresa).Any()) continue;
ctlp = new COVATablaLargoPlazo();
ctlp.IdEmpresa = ctlpAnterior.IdEmpresa;
ctlp.Periodo = idPeriodo;
ctlp.NombrePlan = ctlpAnterior.NombrePlan;
ctlp.COVATipoPlanOpcionId = ctlpAnterior.COVATipoPlanOpcionId;
ctlp.COVASegmentoOpcionId = ctlpAnterior.COVASegmentoOpcionId;
ctlp.NivelDinamicaMin = ctlpAnterior.NivelDinamicaMin;
ctlp.NivelDinamicaMax = ctlpAnterior.NivelDinamicaMax;
ctlp.RealPagadoFinalPlan = ctlpAnterior.RealPagadoFinalPlan;
ctlp.AniosEjerce = ctlpAnterior.AniosEjerce;
ctlp.MetodoCalculo = ctlpAnterior.MetodoCalculo;
ctlp.BaseCalculo = ctlpAnterior.BaseCalculo;
ctlp.Save();
}
var respuestasVentas = COVAVentas.Find(x => x.Periodo == (periodoAnterior));
COVAVentas cv;
foreach (var cvAnterior in respuestasVentas)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == cvAnterior.IdEmpresa).Any()) continue;
cv = new COVAVentas();
cv.IdEmpresa = cvAnterior.IdEmpresa;
cv.CuentaVentas = cvAnterior.CuentaVentas;
cv.ComentariosAdicionales = cvAnterior.ComentariosAdicionales;
cv.RetiroVoluntarioOpcionId = cvAnterior.RetiroVoluntarioOpcionId;
cv.RetiroVoluntarioOtroDesc = cvAnterior.RetiroVoluntarioOtroDesc;
cv.RetiroEmpresaOpcionId = cvAnterior.RetiroEmpresaOpcionId;
cv.RetiroEmpresaOtroDesc = cvAnterior.RetiroEmpresaOtroDesc;
cv.Periodo = idPeriodo;
cv.Save();
}
var tablaVentasAnterior = COVATablaVentas.Find(x => x.Periodo == (periodoAnterior));
COVATablaVentas ctv;
foreach (var ctvAnterior in tablaVentasAnterior)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == ctvAnterior.IdEmpresa).Any()) continue;
ctv = new COVATablaVentas();
ctv.IdEmpresa = ctvAnterior.IdEmpresa;
ctv.Periodo = idPeriodo;
ctv.COVASegmentoOpcionId = ctvAnterior.COVASegmentoOpcionId;
ctv.COVAPeriodicidadOpcionId = ctvAnterior.COVAPeriodicidadOpcionId;
ctv.Minimo = ctvAnterior.Minimo;
ctv.Target = ctvAnterior.Target;
ctv.Maximo = ctvAnterior.Maximo;
ctv.RealAnualizado = ctvAnterior.RealAnualizado;
ctv.MetodoCalculo = ctvAnterior.MetodoCalculo;
ctv.BaseCalculo = ctvAnterior.BaseCalculo;
ctv.Save();
}
var respuestasGenerales = COVAGenerales.Find(x => x.Periodo == (periodoAnterior));
COVAGenerales cg;
foreach (var cgAnterior in respuestasGenerales)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == cgAnterior.IdEmpresa).Any()) continue;
cg = new COVAGenerales();
cg.IdEmpresa = cgAnterior.IdEmpresa;
cg.AccionesPorSituacionActual = cgAnterior.AccionesPorSituacionActual;
cg.ComentariosAccionesSituacionActual = cgAnterior.ComentariosAccionesSituacionActual;
cg.TomaCuentaSituacionDefinicionObjetivos = cgAnterior.TomaCuentaSituacionDefinicionObjetivos;
cg.Periodo = idPeriodo;
cg.Save();
}
}
Am I doing it the wrong way? At this point, I am not sure if this is a Subsonic bug or if I need to manually close the connection myself somehow.
I've googled for posts about similar problems when using subsonic, but none have come up. The usual cause for the error I get is not closing the SqlDataReader, but I honestly do not believe Subsonic is not closing it..and Im using the latest version.
Any ideas? Any help is greatly appreciated.
Any time you have a loop on an ORM-based object you have to consider there's probably an N+1 issue. I can't see your model, but I'll bet that in your loop you're executing a number of additional queries.
I know that Save() fires and closes an ExecuteScalar() - this should not leave a connection open. However, if you're fetching related records inside that loop - yeah that could have problems.
So - I would recommend using a profiler of some kind and the debugger to step through your loop - see what queries are made.
Alternatively - this is ripe for using the BatchInsert stuff which would keep everything in a nice, tidy single-connection transaction.
Read here for more:
http://subsonic.wekeroad.com/docs/Linq_Inserts

Resources