Hi all, here a very easy lwebcode free script to split file in C#
// calls example
...
int iSplittedFileSize = 1024 * 8;MergeFile(@"C:\script\", iSplittedFileSize, @"C:\LwebCodeMergeFile\");
...
public static void MergeFile(string inputfoldername1, string SaveFileFolder)
{
string[] tmpfiles = Directory.GetFiles(inputfoldername1, "*.tmp");
FileStream outPutFile = null;
string PrevFileName = "";
foreach (string tempFile in tmpfiles)
{
string fileName = Path.GetFileNameWithoutExtension(tempFile);
string baseFileName = fileName.Substring(0, fileName.IndexOf(Convert.ToChar(".")));
string extension = Path.GetExtension(fileName);
if (!PrevFileName.Equals(baseFileName))
{
if (outPutFile != null)
{
outPutFile.Flush();
outPutFile.Close();
}
outPutFile = new FileStream(SaveFileFolder + "\\" + baseFileName + extension, FileMode.OpenOrCreate, FileAccess.Write);
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
FileStream inputTempFile = new FileStream(tempFile, FileMode.OpenOrCreate, FileAccess.Read);
while ((bytesRead = inputTempFile.Read(buffer, 0, 1024)) > 0)
outPutFile.Write(buffer, 0, bytesRead);
inputTempFile.Close();
PrevFileName = baseFileName;
}
}
Hope you like it ;)
Showing posts with label Oop. Show all posts
Showing posts with label Oop. Show all posts
Thursday, 20 July 2017
Friday, 30 June 2017
C# Split File
Hi all, here a very easy lwebcode free script to split file in C#
// calls example
...
int iSplittedFileSize = 1024 * 8;
SplitFile(@"C:\script\lwebcode.bak", iSplittedFileSize, @"C:\script\");
...
public static void SplitFile(string inputFile, int chunkSize, string path)
{
const int BUFFER_SIZE = 20 * 1024; //2 Kb for each file
byte[] buffer = new byte[BUFFER_SIZE];
string baseFileName = Path.GetFileNameWithoutExtension(inputFile);
string Extension = Path.GetExtension(inputFile);
using (Stream input = File.OpenRead(inputFile))
{
int index = 0;
while (input.Position < input.Length)
{
string sFinalName = path + "\\" + baseFileName + "." + index.ToString().PadLeft(5, Convert.ToChar("0")) + Extension + ".tmp";
using (Stream output = File.Create(sFinalName))
{
int remaining = chunkSize, bytesRead;
while (remaining > 0 && (bytesRead = input.Read(buffer, 0,
Math.Min(remaining, BUFFER_SIZE))) > 0)
{
output.Write(buffer, 0, bytesRead);
remaining -= bytesRead;
}
}
index++;
System.Threading.Thread.Sleep(500);
}
}
}
Hope you like it ;)
// calls example
...
int iSplittedFileSize = 1024 * 8;
SplitFile(@"C:\script\lwebcode.bak", iSplittedFileSize, @"C:\script\");
...
public static void SplitFile(string inputFile, int chunkSize, string path)
{
const int BUFFER_SIZE = 20 * 1024; //2 Kb for each file
byte[] buffer = new byte[BUFFER_SIZE];
string baseFileName = Path.GetFileNameWithoutExtension(inputFile);
string Extension = Path.GetExtension(inputFile);
using (Stream input = File.OpenRead(inputFile))
{
int index = 0;
while (input.Position < input.Length)
{
string sFinalName = path + "\\" + baseFileName + "." + index.ToString().PadLeft(5, Convert.ToChar("0")) + Extension + ".tmp";
using (Stream output = File.Create(sFinalName))
{
int remaining = chunkSize, bytesRead;
while (remaining > 0 && (bytesRead = input.Read(buffer, 0,
Math.Min(remaining, BUFFER_SIZE))) > 0)
{
output.Write(buffer, 0, bytesRead);
remaining -= bytesRead;
}
}
index++;
System.Threading.Thread.Sleep(500);
}
}
}
Hope you like it ;)
Wednesday, 17 May 2017
C# Windows Service Debug
Hi all, here an easy example to make a debug on C# Windows Service ,
Implementation of Code founded on:
https://www.codeproject.com/Articles/14353/Creating-a-Basic-Windows-Service-in-C
With this useful example you create a Single *.exe file , but if you start the debugger
you can't debug the code with Visual Studio, Here is how to do:
First, make all step writed on CodeProject(in future reference I call this project "CodeProjectWS"), after you need to do this:
Right Clik on Current Solution -> Add -> New Project
On Project Type select Windows Consolle Application
select a name for new project, I choose :"LwebCodeWinDbg" -> Ok
Now in New Project "LwebCodeWinDbg" right-click the project name and go to:
[Add]->[Class]. Name the class "LwebCodeWindowsService.cs" and then hit OK.
Open class "LwebCodeWindowsService" and put this code:
namespace LwebCodeWinDbg
{
public class LwebCodeWindowsService
{
public static void WindowsServiceStart()
{
System.IO.File.WriteAllText("c:\\LwebCodeTetsService.txt", DateTime.Now.ToString());
}
}
}
Now in New Project "LwebCodeWinDbg" open Program.cs and paste this code over Main Function:
namespace LwebCodeWinDbg
{
class Program
{
static void Main(string[] args)
{
//put debug breakpoint on this istruction:
LwebCodeWindowsService.WindowsServiceStart();
}
}
}
Now Open "CodeProjectWS" , right Clik on "Reference"-> Add Reference
in left pane select: "Solution" -> Browse... and browse to "LwebCodeWinDbg" Project and then hit OK.
Open WindowsService.cs
and paste this code on OnStart Event:
protected override void OnStart(string[] args)
{
base.OnStart(args);
LwebCodeWinDbg.LwebCodeWindowsService.WindowsServiceStart();
}
with this istruction you can call the same function from Windows Service and Windows Consolle Application.
To debug the Windows service right click on "LwebCodeWinDbg" -> Set as Startup Project
F5 to start debug.
Hope it helps
Implementation of Code founded on:
https://www.codeproject.com/Articles/14353/Creating-a-Basic-Windows-Service-in-C
With this useful example you create a Single *.exe file , but if you start the debugger
you can't debug the code with Visual Studio, Here is how to do:
First, make all step writed on CodeProject(in future reference I call this project "CodeProjectWS"), after you need to do this:
Right Clik on Current Solution -> Add -> New Project
On Project Type select Windows Consolle Application
select a name for new project, I choose :"LwebCodeWinDbg" -> Ok
Now in New Project "LwebCodeWinDbg" right-click the project name and go to:
[Add]->[Class]. Name the class "LwebCodeWindowsService.cs" and then hit OK.
Open class "LwebCodeWindowsService" and put this code:
namespace LwebCodeWinDbg
{
public class LwebCodeWindowsService
{
public static void WindowsServiceStart()
{
System.IO.File.WriteAllText("c:\\LwebCodeTetsService.txt", DateTime.Now.ToString());
}
}
}
Now in New Project "LwebCodeWinDbg" open Program.cs and paste this code over Main Function:
namespace LwebCodeWinDbg
{
class Program
{
static void Main(string[] args)
{
//put debug breakpoint on this istruction:
LwebCodeWindowsService.WindowsServiceStart();
}
}
}
Now Open "CodeProjectWS" , right Clik on "Reference"-> Add Reference
in left pane select: "Solution" -> Browse... and browse to "LwebCodeWinDbg" Project and then hit OK.
Open WindowsService.cs
and paste this code on OnStart Event:
protected override void OnStart(string[] args)
{
base.OnStart(args);
LwebCodeWinDbg.LwebCodeWindowsService.WindowsServiceStart();
}
with this istruction you can call the same function from Windows Service and Windows Consolle Application.
To debug the Windows service right click on "LwebCodeWinDbg" -> Set as Startup Project
F5 to start debug.
Hope it helps
Thursday, 26 January 2017
C# RSS 2.0 Atom FEED Writer
Hi All, here a lwebode's C# class to generate a Feed rss 2.0 ,
it can generate by code or by SQL with dataset create a new class naming it “RSS_Writer” and just copy and paste code below.
//LWEBCODE C# RSS 2.0 Atom FEED Writer Usage example:
//Here C# LWEBCODE RSS 2.0 Atom FEED Writer Class
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.IO;
/// RSS_Writer
/// generated by LWEBCODE
/// http://lwebcode.blogspot.com/
///
///
public class RSS_Writer
{
public RSS_Writer()
{
//string path = HttpContext.Current.Server.MapPath("rss.xml");
public static int NewRss(string path, string sTitle, string sLink, string sDescription, string sLanguage)
{
//XmlTextWriter writer = OpenXMLWriter(path);
/*writer.WriteStartDocument();
writer.WriteProcessingInstruction("xml-stylesheet", "type='text/xsl' href='lead.xsl'");
writer.WriteStartElement("rss");
writer.WriteAttributeString("version", "2.0");
writer.WriteStartElement("channel");
writer.WriteElementString("title", sTitle);
writer.WriteElementString("link", sLink);
writer.WriteElementString("description", sDescription);
writer.WriteElementString("language", sLanguage);
string GMTDate = System.TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now).ToString("r");
writer.WriteElementString("lastBuildDate", GMTDate);
*/
XmlDocument xd = new XmlDocument();
//xd.Load(path);
XmlNode xn;
xn = xd.CreateNode(XmlNodeType.Element, "rss", null);
XmlAttribute xa;
xa = xd.CreateAttribute("version");
xa.Value = "2.0";
xn.Attributes.Append(xa);
xd.AppendChild(xn);
xn = xd.CreateNode(XmlNodeType.Element, "channel", null);
xd.SelectSingleNode("//rss").AppendChild(xn);
xn = xd.CreateNode(XmlNodeType.Element, "title", null);
xn.InnerText = sTitle;
xd.SelectSingleNode("//channel").AppendChild(xn);
xn = xd.CreateNode(XmlNodeType.Element, "link", null);
xn.InnerText = sLink;
xd.SelectSingleNode("//channel").InsertAfter(xn, xd.SelectSingleNode("//title"));
xn = xd.CreateNode(XmlNodeType.Element, "description", null);
xn.InnerText = sDescription;
xd.SelectSingleNode("//channel").InsertAfter(xn, xd.SelectSingleNode("//link"));
xn = xd.CreateNode(XmlNodeType.Element, "language", null);
xn.InnerText = sLanguage;
xd.SelectSingleNode("//channel").InsertAfter(xn, xd.SelectSingleNode("//description"));
string GMTDate = System.TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now).ToString("r");
xn = xd.CreateNode(XmlNodeType.Element, "lastBuildDate", null);
xn.InnerText = GMTDate;
xd.SelectSingleNode("//channel").InsertAfter(xn, xd.SelectSingleNode("//language"));
XmlTextWriter writer = OpenXMLWriter(path, false);
xd.Save(writer);
CloseXMLWriter(writer);
return 0;
}
public static int AddItems(string path, string sTitle, string sLink, string sDescription, string sGuid)
{
UpdateRssHEAD(path);
XmlDocument xd = new XmlDocument();
xd.Load(path);
XmlNode xn = xd.CreateNode(XmlNodeType.Element, "item", null);
XmlNode xn2;
xn2 = xd.CreateNode(XmlNodeType.Element, "title", null);
xn2.InnerText = sTitle;
xn.AppendChild(xn2);
xn2 = xd.CreateNode(XmlNodeType.Element, "link", null);
xn2.InnerText = sLink;
xn.AppendChild(xn2);
xn2 = xd.CreateNode(XmlNodeType.Element, "description", null);
xn2.InnerText = sDescription;
xn.AppendChild(xn2);
string GMTDate = System.TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now).ToString("r");
xn2 = xd.CreateNode(XmlNodeType.Element, "pubDate", null);
xn2.InnerText = GMTDate;
xn.AppendChild(xn2);
xn2 = xd.CreateNode(XmlNodeType.Element, "guid", null);
xn2.InnerText = sGuid;
xn.AppendChild(xn2);
xd.SelectSingleNode("//channel").InsertAfter(xn, xd.SelectSingleNode("//lastBuildDate"));
XmlTextWriter writer = OpenXMLWriter(path, false);
xd.Save(writer);
CloseXMLWriter(writer);
return 0;
}
public static int CreateRssFromDataSet(string path, DataSet ds, string sTitleField, string sLinkField, string sDescriptionField, string sGuidField)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
AddItems(path, ds.Tables[0].Rows[i][sTitleField].ToString(), ds.Tables[0].Rows[i][sLinkField].ToString(), ds.Tables[0].Rows[i][sDescriptionField].ToString(), ds.Tables[0].Rows[i][sGuidField].ToString());
}
return 0;
}
private static int UpdateRssHEAD(string path)
{
XmlDocument xd = new XmlDocument();
xd.Load(path);
XmlNode nodeCh = xd.DocumentElement.SelectSingleNode("//channel");
XmlNode xnd = xd.DocumentElement.SelectSingleNode("//lastBuildDate");
string GMTDate = System.TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now).ToString("r");
xnd.InnerText = GMTDate;
nodeCh.ReplaceChild(xnd, xnd);
XmlTextWriter writer = OpenXMLWriter(path, false);
xd.Save(writer);
CloseXMLWriter(writer);
return 0;
}
private static XmlTextWriter OpenXMLWriter(string path)
{
XmlTextWriter writer;
if (!File.Exists(path))
{
writer = new XmlTextWriter(path, System.Text.Encoding.UTF8);
}
else
{
Stream xmlFile = new System.IO.FileStream(path, FileMode.Append);
writer = new XmlTextWriter(xmlFile, System.Text.Encoding.UTF8);
}
return writer;
}
private static XmlTextWriter OpenXMLWriter(string path, bool Append)
{
XmlTextWriter writer;
if ((!File.Exists(path)) || (!Append))
{
writer = new XmlTextWriter(path, System.Text.Encoding.UTF8);
}
else
{
Stream xmlFile = new System.IO.FileStream(path, FileMode.Append);
writer = new XmlTextWriter(xmlFile, System.Text.Encoding.UTF8);
}
return writer;
}
private static void CloseXMLWriter(XmlTextWriter writer)
{
writer.WriteEndDocument();
writer.Flush();
writer.Close();
}
}
it can generate by code or by SQL with dataset create a new class naming it “RSS_Writer” and just copy and paste code below.
//LWEBCODE C# RSS 2.0 Atom FEED Writer Usage example:
//To generate a feed by code (in this case rss will placed into root directory of websites):
string RssPath = Server.MapPath("../rss.xml");
RSS_Writer.NewRss(RssPath, "FEED Title", "www.exmple.com", "Header Description of feed", "en-us");
//to add a items programmatically:
RSS_Writer.AddItems(RssPath, "your title", "link to this article", "Description", "");
//to generate rss from SQL after have filled a Dataset (ds) :
RSS_Writer.CreateRssFromDataSet(RssPath, ds, "titleFiled", "LnkField", "DescrField", "GuidField");//Here C# LWEBCODE RSS 2.0 Atom FEED Writer Class
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.IO;
/// RSS_Writer
/// generated by LWEBCODE
/// http://lwebcode.blogspot.com/
///
///
public class RSS_Writer
{
public RSS_Writer()
{
//string path = HttpContext.Current.Server.MapPath("rss.xml");
public static int NewRss(string path, string sTitle, string sLink, string sDescription, string sLanguage)
{
//XmlTextWriter writer = OpenXMLWriter(path);
/*writer.WriteStartDocument();
writer.WriteProcessingInstruction("xml-stylesheet", "type='text/xsl' href='lead.xsl'");
writer.WriteStartElement("rss");
writer.WriteAttributeString("version", "2.0");
writer.WriteStartElement("channel");
writer.WriteElementString("title", sTitle);
writer.WriteElementString("link", sLink);
writer.WriteElementString("description", sDescription);
writer.WriteElementString("language", sLanguage);
string GMTDate = System.TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now).ToString("r");
writer.WriteElementString("lastBuildDate", GMTDate);
*/
XmlDocument xd = new XmlDocument();
//xd.Load(path);
XmlNode xn;
xn = xd.CreateNode(XmlNodeType.Element, "rss", null);
XmlAttribute xa;
xa = xd.CreateAttribute("version");
xa.Value = "2.0";
xn.Attributes.Append(xa);
xd.AppendChild(xn);
xn = xd.CreateNode(XmlNodeType.Element, "channel", null);
xd.SelectSingleNode("//rss").AppendChild(xn);
xn = xd.CreateNode(XmlNodeType.Element, "title", null);
xn.InnerText = sTitle;
xd.SelectSingleNode("//channel").AppendChild(xn);
xn = xd.CreateNode(XmlNodeType.Element, "link", null);
xn.InnerText = sLink;
xd.SelectSingleNode("//channel").InsertAfter(xn, xd.SelectSingleNode("//title"));
xn = xd.CreateNode(XmlNodeType.Element, "description", null);
xn.InnerText = sDescription;
xd.SelectSingleNode("//channel").InsertAfter(xn, xd.SelectSingleNode("//link"));
xn = xd.CreateNode(XmlNodeType.Element, "language", null);
xn.InnerText = sLanguage;
xd.SelectSingleNode("//channel").InsertAfter(xn, xd.SelectSingleNode("//description"));
string GMTDate = System.TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now).ToString("r");
xn = xd.CreateNode(XmlNodeType.Element, "lastBuildDate", null);
xn.InnerText = GMTDate;
xd.SelectSingleNode("//channel").InsertAfter(xn, xd.SelectSingleNode("//language"));
XmlTextWriter writer = OpenXMLWriter(path, false);
xd.Save(writer);
CloseXMLWriter(writer);
return 0;
}
public static int AddItems(string path, string sTitle, string sLink, string sDescription, string sGuid)
{
UpdateRssHEAD(path);
XmlDocument xd = new XmlDocument();
xd.Load(path);
XmlNode xn = xd.CreateNode(XmlNodeType.Element, "item", null);
XmlNode xn2;
xn2 = xd.CreateNode(XmlNodeType.Element, "title", null);
xn2.InnerText = sTitle;
xn.AppendChild(xn2);
xn2 = xd.CreateNode(XmlNodeType.Element, "link", null);
xn2.InnerText = sLink;
xn.AppendChild(xn2);
xn2 = xd.CreateNode(XmlNodeType.Element, "description", null);
xn2.InnerText = sDescription;
xn.AppendChild(xn2);
string GMTDate = System.TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now).ToString("r");
xn2 = xd.CreateNode(XmlNodeType.Element, "pubDate", null);
xn2.InnerText = GMTDate;
xn.AppendChild(xn2);
xn2 = xd.CreateNode(XmlNodeType.Element, "guid", null);
xn2.InnerText = sGuid;
xn.AppendChild(xn2);
xd.SelectSingleNode("//channel").InsertAfter(xn, xd.SelectSingleNode("//lastBuildDate"));
XmlTextWriter writer = OpenXMLWriter(path, false);
xd.Save(writer);
CloseXMLWriter(writer);
return 0;
}
public static int CreateRssFromDataSet(string path, DataSet ds, string sTitleField, string sLinkField, string sDescriptionField, string sGuidField)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
AddItems(path, ds.Tables[0].Rows[i][sTitleField].ToString(), ds.Tables[0].Rows[i][sLinkField].ToString(), ds.Tables[0].Rows[i][sDescriptionField].ToString(), ds.Tables[0].Rows[i][sGuidField].ToString());
}
return 0;
}
private static int UpdateRssHEAD(string path)
{
XmlDocument xd = new XmlDocument();
xd.Load(path);
XmlNode nodeCh = xd.DocumentElement.SelectSingleNode("//channel");
XmlNode xnd = xd.DocumentElement.SelectSingleNode("//lastBuildDate");
string GMTDate = System.TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now).ToString("r");
xnd.InnerText = GMTDate;
nodeCh.ReplaceChild(xnd, xnd);
XmlTextWriter writer = OpenXMLWriter(path, false);
xd.Save(writer);
CloseXMLWriter(writer);
return 0;
}
private static XmlTextWriter OpenXMLWriter(string path)
{
XmlTextWriter writer;
if (!File.Exists(path))
{
writer = new XmlTextWriter(path, System.Text.Encoding.UTF8);
}
else
{
Stream xmlFile = new System.IO.FileStream(path, FileMode.Append);
writer = new XmlTextWriter(xmlFile, System.Text.Encoding.UTF8);
}
return writer;
}
private static XmlTextWriter OpenXMLWriter(string path, bool Append)
{
XmlTextWriter writer;
if ((!File.Exists(path)) || (!Append))
{
writer = new XmlTextWriter(path, System.Text.Encoding.UTF8);
}
else
{
Stream xmlFile = new System.IO.FileStream(path, FileMode.Append);
writer = new XmlTextWriter(xmlFile, System.Text.Encoding.UTF8);
}
return writer;
}
private static void CloseXMLWriter(XmlTextWriter writer)
{
writer.WriteEndDocument();
writer.Flush();
writer.Close();
}
}
/*IMPORTANT NOTES:
Then to configure IIS, follow these steps:
Open IIS and navigate to the appropriate application/website
Right click and choose ‘Properties’ from the menu
Select the ‘HTTP Headers’ tab
There’s a section at the bottom entitled ‘MIME Map’, and from that click on ‘File Types’
Click ‘New Type’
For the ‘Associated extension’ enter .rss
And for ‘Content type (MIME)’ enter application/rss+xml
Click ‘OK’ and then ‘Apply’
Feel free to restart the IIS server, although you shouldn’t have to.
Ensure that the HTML page link to the RSS file includes the RSS extension, e.g.
*/
} Thursday, 19 January 2017
C# - SQL Class Implementation
Hi All, Here LWebCode's class to directly run SQL statements whitout declare and initialize Connection and Command objects.
The class works for aspx page and also for Windows Forms,
in windows forms remember to change initial parameters like connection string, CodeID ect..
Very useful to write less code
Optionally in 2 ArrayList we can pass parameters and relative values
Class usage Example:
//Put this at top of your *.cs file in aspx page, or Windows Form Class
using LWebCode;
//simple calling function
public void Calls_iSQL_Class()
{
string cnString = ConfigurationManager.ConnectionStrings[0].ConnectionString;
string sCodeID = Request.QueryString["qryPar1"].ToString();
string sDate = Request.QueryString["qryPar2"].ToString();
ArrayList aFields = new ArrayList();
ArrayList aValues = new ArrayList();
aFields.Add("@CODEID");
aFields.Add("@DATE");
aValues.Add(sCodeID);
aValues.Add(sDate);
//Performing SQL INSERT and UPDATE Statement:
//Call Example with Parameters more secure
int res = iSQL.ExecuteNonQuery(cnString , "INSERT INTO MY_TABLE (CODE,DATE_R) VALUES (@CODEID,@DATE)",aFields ,aValues);
//Call Example without Parameters less secure don't use it, or use it carrefully recomended use for debugging SQL statement
int res2 = iSQL.ExecuteNonQuery(cnString , "UPDATE MY_TABLE SET DATE_R=NULL WHERE CODE=1235LWEBCODE", null , null);
//Performing Fast Reading Value valid only for 1 record with SQL SELECT Statemet
string sres = iSQL.ExecuteReader(cnString , "SELECT TOP 1 DATE_R FROM MY_TABLE WHERE CODE=1235LWEBCODE", null , null);
}
HERE THE LWebCode's CLASS:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections;
///
/// Class to execute sql statement like SELECT,UPDATE,INSERT other
/// whitout initialize connection and command
///
namespace LWebCode
{
public class iSQL
{
public iSQL()
{
}
///
/// Esegue un ExecuteNonQuery con un Singolo Parametro
///
/// The Connection Strings
/// Sql Statements to execute
/// Field Add '@'
/// Value
///
public static int ExecuteNonQuery(string CnString,string SQL,string Campo,string Valore)
{
cn = new SqlConnection(CnString);
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.Parameters.AddWithValue(Campo, Valore);
cmd.CommandText = SQL;
int ris = cmd.ExecuteNonQuery();
cn.Close();
cn.Dispose();
cmd.Dispose();
return ris;
}
///
/// Execute ExecuteScalar with multiple Parameters
///
/// The Connection Strings
/// Sql Statements to execute
/// Fields Array with @
/// Values Array
///
public static int ExecuteNonQuery(string CnString, string SQL, ArrayList Fields ,ArrayList Values)
{
SqlConnection cn = new SqlConnection(CnString);
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
for (int i = 0; i < Fields.Count; i++)
{
cmd.Parameters.AddWithValue(Fields[i].ToString(), Values[i]);
}
cmd.CommandText = SQL;
int ris=cmd.ExecuteNonQuery();
cn.Close();
cn.Dispose();
cmd.Dispose();
return ris;
}
///
/// Execute ExecuteScalar with multiple Parameters
///
/// The Connection Strings
/// Sql Statements to execute
/// Fields Array
/// Values Array
///
public static int ExecuteScalar(string CnString, string SQL, ArrayList Fields, ArrayList Values)
{
SqlConnection cn = new SqlConnection(CnString);
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
for (int i = 0; i < Fields.Count; i++)
{
cmd.Parameters.AddWithValue(Fields[i].ToString(), Values[i]);
}
cmd.CommandText = SQL;
int ris = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();
cn.Dispose();
cmd.Dispose();
return ris;
}
///
/// Execute Reader which return only 1 value
///
/// The Connection Strings
/// Sql Statements to execute
/// Fields Array
/// Values Array
///
public static string ExecuteReader(string CnString, string SQL, ArrayList Fields, ArrayList Values)
{
SqlConnection cn = new SqlConnection(CnString);
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = SQL;
for (int i = 0; i < Fields.Count; i++)
{
cmd.Parameters.AddWithValue(Fields[i].ToString(), Values[i]);
}
SqlDataReader rd;
rd = cmd.ExecuteReader();
string a = "";
while (rd.Read())
{
a = rd[0].ToString();
}
cmd.Dispose();
cn.Close();
rd.Close();
rd.Dispose();
return a;
}
}
}
The class works for aspx page and also for Windows Forms,
in windows forms remember to change initial parameters like connection string, CodeID ect..
Very useful to write less code
Optionally in 2 ArrayList we can pass parameters and relative values
Class usage Example:
//Put this at top of your *.cs file in aspx page, or Windows Form Class
using LWebCode;
//simple calling function
public void Calls_iSQL_Class()
{
string cnString = ConfigurationManager.ConnectionStrings[0].ConnectionString;
string sCodeID = Request.QueryString["qryPar1"].ToString();
string sDate = Request.QueryString["qryPar2"].ToString();
ArrayList aFields = new ArrayList();
ArrayList aValues = new ArrayList();
aFields.Add("@CODEID");
aFields.Add("@DATE");
aValues.Add(sCodeID);
aValues.Add(sDate);
//Performing SQL INSERT and UPDATE Statement:
//Call Example with Parameters more secure
int res = iSQL.ExecuteNonQuery(cnString , "INSERT INTO MY_TABLE (CODE,DATE_R) VALUES (@CODEID,@DATE)",aFields ,aValues);
//Call Example without Parameters less secure don't use it, or use it carrefully recomended use for debugging SQL statement
int res2 = iSQL.ExecuteNonQuery(cnString , "UPDATE MY_TABLE SET DATE_R=NULL WHERE CODE=1235LWEBCODE", null , null);
//Performing Fast Reading Value valid only for 1 record with SQL SELECT Statemet
string sres = iSQL.ExecuteReader(cnString , "SELECT TOP 1 DATE_R FROM MY_TABLE WHERE CODE=1235LWEBCODE", null , null);
}
HERE THE LWebCode's CLASS:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections;
///
/// Class to execute sql statement like SELECT,UPDATE,INSERT other
/// whitout initialize connection and command
///
namespace LWebCode
{
public class iSQL
{
public iSQL()
{
}
///
/// Esegue un ExecuteNonQuery con un Singolo Parametro
///
/// The Connection Strings
/// Sql Statements to execute
/// Field Add '@'
/// Value
///
public static int ExecuteNonQuery(string CnString,string SQL,string Campo,string Valore)
{
cn = new SqlConnection(CnString);
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.Parameters.AddWithValue(Campo, Valore);
cmd.CommandText = SQL;
int ris = cmd.ExecuteNonQuery();
cn.Close();
cn.Dispose();
cmd.Dispose();
return ris;
}
///
/// Execute ExecuteScalar with multiple Parameters
///
/// The Connection Strings
/// Sql Statements to execute
/// Fields Array with @
/// Values Array
///
public static int ExecuteNonQuery(string CnString, string SQL, ArrayList Fields ,ArrayList Values)
{
SqlConnection cn = new SqlConnection(CnString);
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
for (int i = 0; i < Fields.Count; i++)
{
cmd.Parameters.AddWithValue(Fields[i].ToString(), Values[i]);
}
cmd.CommandText = SQL;
int ris=cmd.ExecuteNonQuery();
cn.Close();
cn.Dispose();
cmd.Dispose();
return ris;
}
///
/// Execute ExecuteScalar with multiple Parameters
///
/// The Connection Strings
/// Sql Statements to execute
/// Fields Array
/// Values Array
///
public static int ExecuteScalar(string CnString, string SQL, ArrayList Fields, ArrayList Values)
{
SqlConnection cn = new SqlConnection(CnString);
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
for (int i = 0; i < Fields.Count; i++)
{
cmd.Parameters.AddWithValue(Fields[i].ToString(), Values[i]);
}
cmd.CommandText = SQL;
int ris = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();
cn.Dispose();
cmd.Dispose();
return ris;
}
///
/// Execute Reader which return only 1 value
///
/// The Connection Strings
/// Sql Statements to execute
/// Fields Array
/// Values Array
///
public static string ExecuteReader(string CnString, string SQL, ArrayList Fields, ArrayList Values)
{
SqlConnection cn = new SqlConnection(CnString);
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = SQL;
for (int i = 0; i < Fields.Count; i++)
{
cmd.Parameters.AddWithValue(Fields[i].ToString(), Values[i]);
}
SqlDataReader rd;
rd = cmd.ExecuteReader();
string a = "";
while (rd.Read())
{
a = rd[0].ToString();
}
cmd.Dispose();
cn.Close();
rd.Close();
rd.Dispose();
return a;
}
}
}
Labels:
c#,
Class,
CommandText,
Database,
debugging,
ExecuteNonQuery,
ExecuteReader,
ExecuteScalar,
iSQL,
lwebcode,
Microsoft SQL Server,
MSSQL,
Oop,
Parameters,
SqlCommand,
SqlConnection,
Table,
tool,
View
Subscribe to:
Posts (Atom)