Monday, January 23, 2012

Centrate div with css

#warning {
width:740px;
left:50%;
top:100px;
margin-left:-370px;
position:fixed;
z-index:10000;
}

//fix for ie6
* html #warning {position:absolute;}

Thursday, January 5, 2012

Run application c# with another username

using System;
using System.Web;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.IO;
using System.Configuration;

///
/// FileAccess
public class FileAccessUtility
{

#region Constructor
public FileAccessUtility()
{
}
#endregion
#region Const
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext impersonationContext;
#endregion
#region DllImport
[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern bool RevertToSelf();

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);

#endregion


#region Methods




public void Copy(string Source, string Destionation)
{
string user, pass, domain;
user = ""; //ConfigurationManager.AppSettings["UserFileAccess"].ToString();
pass = ""; //ConfigurationManager.AppSettings["PassUserFileAccess"].ToString();
domain = ""; //ConfigurationManager.AppSettings["DomainUserFileAccess"].ToString();

if (impersonateValidUser(user, domain, pass))
{
File.Copy(Source, Destionation);
undoImpersonation();
}
else
{
throw new Exception("Autentificarea a esuat pentru userul: " + domain + "\\" + user);
}
}

public void WriteToFile(string filePath, ref byte[] Buffer)
{
string user = "", pass = "", domain = "";
//user = ConfigurationManager.AppSettings["UserFileAccess"].ToString();
//pass = ConfigurationManager.AppSettings["PassUserFileAccess"].ToString();
//domain = ConfigurationManager.AppSettings["DomainUserFileAccess"].ToString();

if (impersonateValidUser(user, domain, pass))
{
WriteFile(filePath, ref Buffer);
undoImpersonation();
}
else
{
throw new Exception("Autentificarea a esuat pentru userul: " + domain + "\\" + user);
}
}

public byte[] ReadFromFile(string filePath)
{
string user = "", pass = "", domain = "";
byte[] buffer;

//user = ConfigurationManager.AppSettings["UserFileAccess"].ToString();
//pass = ConfigurationManager.AppSettings["PassUserFileAccess"].ToString();
//domain = ConfigurationManager.AppSettings["DomainUserFileAccess"].ToString();

if (impersonateValidUser(user, domain, pass))
{
buffer = ReadFile(filePath);
undoImpersonation();
return buffer;
}
else
{
throw new Exception("Autentificarea a esuat pentru userul: " + domain + "\\" + user);
}
}

private void WriteFile(string filePath, ref byte[] Buffer)
{
if (!Directory.Exists(Path.GetDirectoryName(filePath)))
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
FileStream newFile = new FileStream(filePath, FileMode.CreateNew);
newFile.Write(Buffer, 0, Buffer.Length);
newFile.Close();
}

private byte[] ReadFile(string filePath)
{
byte[] buffer;
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

int length = (int)fileStream.Length; // get file length
buffer = new byte[length]; // create buffer
int count; // actual number of bytes read
int sum = 0; // total number of bytes read

// read until Read method returns 0 (end of the stream has been reached)
while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
sum += count; // sum is a buffer offset for next reading


fileStream.Close();
return buffer;


}

private bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;

if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}

private void undoImpersonation()
{
impersonationContext.Undo();
}




#endregion
}





Call the class

FileAccessUtility fileAcces;
byte[] myData;
HttpPostedFile myFile;
if (fileUploadDocumentSolicitant.PostedFile.InputStream.Length < 7000000)
{
Random rnd = new Random();
fileAcces = new FileAccessUtility();
}

Wednesday, January 4, 2012

C# - Serialize/Deserialize object

public static string SerObj(object rspJ)
{
string serObj = null;

MemoryStream ms = new MemoryStream();
BinaryFormatter bf1 = new BinaryFormatter();
bf1.Serialize(ms, rspJ);
serObj = Convert.ToBase64String(ms.ToArray());

return serObj;
}

public static string SerObjXML(object rspJ, Type type)
{
string serObj = null;

MemoryStream ms = new MemoryStream();
XmlSerializer bf1 = new XmlSerializer(type);
bf1.Serialize(ms, rspJ);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
serObj = sr.ReadToEnd();

return serObj;
}

public static object DeSerObjXML(string xml, Type type)
{
XmlSerializer xs = new XmlSerializer(type);
MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xml));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
return xs.Deserialize(memoryStream);
}

public static
RspTestXML DeSerObj(string stringObj)
{
RspTestXML rspTestXML = null;

byte[] theByteArray = Convert.FromBase64String(stringObj);

MemoryStream ms1 = new MemoryStream(theByteArray);
BinaryFormatter bf11 = new BinaryFormatter();
ms1.Position = 0;

rspTestXML = (
RspTestXML)bf11.Deserialize(ms1);

return rspTestXML;
}


private static Byte[] StringToUTF8ByteArray(string pXmlString)
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] byteArray = encoding.GetBytes(pXmlString);
return byteArray;
}

Create Trigger log

create TRIGGER [dbo].[table_Logger] ON [dbo].table
AFTER INSERT,DELETE,UPDATE
AS
BEGIN
SET NOCOUNT ON;

declare @Actiune varchar(50),
@HostName varchar(50),
@SQL nvarchar(500),
@d int,
@i int,
@event int

set @HostName = null

select @HostName = hostname
from master..sysprocesses
where loginame = user_name()

select @HostName = isnull(@HostName, '?'), @d = 0, @i = 0
if exists (select top 1 1 from inserted)
select @i = 1
if exists (select top 1 1 from deleted)
select @d = 1

if @d=1 and @i=1
select @event = 1 /*update*/
else
begin
if @i=1 and @d = 0
select @event = 2 /*insert*/
if @d = 1 and @i = 0
select @event = 3 /*delete*/
end


if @event = 1
begin
insert into table_LOG
select *, 'deleted' , system_user, 'update', getdate(), @HostName
from deleted

insert into table_LOG
select *, 'inserted' , system_user, 'update', getdate(), @HostName
from inserted
end
else if @event = 2
insert into OJ_GrupuriDetaliiSuplimentare_LOG
select *, 'inserted' , system_user, 'insert', getdate(), @HostName
from inserted
else if @event = 3
insert into table_LOG
select *, 'deleted' , system_user, 'delete', getdate(), @HostName
from deleted

end


Replace Table With your table
The log table has the following structure:
create table "table_LOG"
(
.............
[TabelSursa] [varchar](100) NULL,
[NumeUtilizatorLog] [varchar](100) NULL,
[Actiune] [varchar](20) NULL,
[DataLog] [datetime] NULL,
[HostName] [varchar](50) NULL
)

Monday, November 21, 2011

Show xml in tabelar format

< HTML >

< HEAD >
< TITLE >Show XML Content< / TITLE >
< / HEAD >

< BODY >
< XML ID="MyXMLdata" Name="xmlData" SRC="file.xml" >< / XML >

< TABLE ID="XMLTable" DATASRC="#MyXMLdata" BORDER="1" cellpadding="2" cellspacing="0" >
< THEAD >
< TH >column 1< / TH >
< TH >Column 2< / TH >
< / THEAD >

< TR >
< TD >
< B >< Span DATAFLD="ID" >< / SPAN >< / B >
< / TD >
< TD >
< SPAN DATAFLD="TRNREF" >< / SPAN >
< / TD >

< / TR >
< / TABLE >
< / BODY >
< / HTML >

Wednesday, November 16, 2011

Prevent Code injection

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace sqlInjection
{
class Program
{
private static string proxy = "";
private static string port = "";
private static string user = @"";
private static string pass = "";


private static void SearchComponents(string htmlContent, string component, List httpControls)
{
bool finish = false;
int positionComponent = 0;
int positionName = 0;
int positionCurrent = 0;
int position = 0;
int positionEqual = 0;
bool beginName = false;
string finishCharacter = " ";

while (finish != true)
{
positionComponent = htmlContent.IndexOf(component,positionCurrent);
if (positionComponent > 0)
{
positionCurrent = positionComponent + 3;
positionName = htmlContent.IndexOf("name", positionCurrent);
position = positionName + 4;
string componentName = "";
bool finishName = false;
finishCharacter = " ";
positionEqual = 0;
beginName = false;

while (!finishName)
{
if (positionEqual == 0)
{
if (htmlContent.Substring(position, 1) == "=")
{
positionEqual = 1;
}
}
else
{
if (beginName == false)
{
if (htmlContent.Substring(position, 1) == " " || htmlContent.Substring(position, 1) == "'" || htmlContent.Substring(position, 1) == "\"")
{
beginName = false;
}
else
{
beginName = true;
componentName = htmlContent.Substring(position, 1);
}
}
else
{

if (htmlContent.Substring(position, 1) == " " || htmlContent.Substring(position, 1) == "'" || htmlContent.Substring(position, 1) == "\"")
{
finishName = true;
}
else
componentName += htmlContent.Substring(position, 1);
}
}

position++;

}
httpControls.Add(componentName);
//httpControls.Add(httmlContent.Substring(componentName, 30));
}
else
{
finish = true;
}


}
}

static void Main(string[] args)
{
string link = "http://site.com";



/*
string injection = "1%3cScRiPt%20%3eprompt%28944524%29%3c%2fScRiPt%3e";
string injectionVerif = "prompt(";
*/
string injection = @"%22onmouseover=prompt(963103)%3E";
string injectionVerif = "onmouseover=prompt(";

WebRequest request = WebRequest.Create(link);
request.Method = "POST";
request.Proxy = new WebProxy(proxy, int.Parse(port));
request.Proxy.Credentials = new NetworkCredential(user,pass);

string postData = "";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;

Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string httmlContent = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();

string searchComponent = "";
List listHTMLComponents = new List();
listHTMLComponents.Add("< select"); listHTMLComponents.Add("< input"); List httpControls = new List();


for (int i = 0; i < listHTMLComponents.Count; i++)
{
searchComponent = listHTMLComponents[i].ToString();
SearchComponents(httmlContent, searchComponent, httpControls);
}


for (int i = 0; i < httpControls.Count; i++)
{

postData += httpControls[i] + "=" + injection + "&";

}

request = WebRequest.Create(link);
request.Method = "POST";
byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
request.Proxy = new WebProxy(proxy, int.Parse(port));
request.Proxy.Credentials = new NetworkCredential(user,pass);

dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
httmlContent = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();

if (httmlContent.Contains(injectionVerif))
{
Console.WriteLine("Injection ");
}

}



}

}

Wednesday, October 26, 2011

Links CBIR

http://www.cs.auckland.ac.nz/compsci708s1c/lectures/Glect-html/topic3c708FSC.htm#scd