tag:blogger.com,1999:blog-89123342008-04-28T04:44:59.239-07:00Marc Boizeau's blogMarcnoreply@blogger.comBlogger37125tag:blogger.com,1999:blog-8912334.post-1165930927114233552006-12-12T05:38:00.000-08:002006-12-12T05:42:08.010-08:00When does the next bus pass?I work in a remote bussiness center downtown Paris. Last weeks I spend nearly 3 hour a days comuting.<br />Every evening, I have to wait for a bus and one time out of two it rain cats and dog.<br />So every evening I check the bus company's web site in order to known at what time the next bus pass to my station.<br />Late in the evening at Office I have no time to loose! So I decide to speed up this repetitive task:<br /><br />A few times ago(lol) I wrote a C# code to perform a web crawling. I used the same technology to code the following extractor. As usual this has been made with VS studio but, use csc.exe (.Net 1.1 framework) to compile it as well. (see previous posts for exact command line)<br /><br /><tt><br /><br />using System;<br />using System.Drawing;<br />using System.Collections;<br />using System.ComponentModel;<br />using System.Windows.Forms;<br />using System.Data;<br />using System.Net;<br />using System.IO;<br />using System.Text;<br />using System.Text.RegularExpressions;<br />namespace bus<br />{<br />/// <summary><br />/// Summary description for Form1.<br />/// </summary><br />public class Form1 : System.Windows.Forms.Form<br />{<br />private System.Windows.Forms.Button button1;<br />private System.Windows.Forms.RichTextBox richTextBox1;<br />private System.Windows.Forms.RichTextBox richTextBox2;<br />/// <summary><br />/// Required designer variable.<br />/// </summary><br />private System.ComponentModel.Container components = null;<br /><br />/// <summary><br />/// Use a regular expression to extract informations from a string<br />/// all matching results are stored in a string array.<br />/// </summary><br />/// <param name="strHTML"></param><br />/// <param name="r"></param><br />/// <returns></returns><br />private static string [] extractReg(string strHTML,Regex r)<br />{<br />Match m;<br /><br />String[] results = new String[101];<br /><br />// Use the Matches method to find all matches in the input string.<br />// Loop through the match collection to retrieve all<br />// matches.<br />int i=0;<br />m = r.Match(strHTML);<br /><br />for (i=0; (m.Success &&amp;amp;amp; i<100); m =" m.NextMatch())"><br />/// Clean up any resources being used.<br />/// </summary><br />protected override void Dispose( bool disposing )<br />{<br />if( disposing )<br />{<br />if (components != null)<br />{<br />components.Dispose();<br />}<br />}<br />base.Dispose( disposing );<br />}<br /><br />#region Windows Form Designer generated code<br />/// <summary><br />/// Required method for Designer support - do not modify<br />/// the contents of this method with the code editor.<br />/// </summary><br />private void InitializeComponent()<br />{<br />this.button1 = new System.Windows.Forms.Button();<br />this.richTextBox1 = new System.Windows.Forms.RichTextBox();<br />this.richTextBox2 = new System.Windows.Forms.RichTextBox();<br />this.SuspendLayout();<br />//<br />// button1<br />//<br />this.button1.Location = new System.Drawing.Point(0, 0);<br />this.button1.Name = "button1";<br />this.button1.Size = new System.Drawing.Size(344, 40);<br />this.button1.TabIndex = 0;<br />this.button1.Text = "check it ";<br />this.button1.Click += new System.EventHandler(this.button1_Click);<br />//<br />// richTextBox1<br />//<br />this.richTextBox1.Location = new System.Drawing.Point(0, 48);<br />this.richTextBox1.Name = "-";<br />this.richTextBox1.Size = new System.Drawing.Size(160, 96);<br />this.richTextBox1.TabIndex = 1;<br />this.richTextBox1.Text = "-";<br />//<br />// richTextBox2<br />//<br />this.richTextBox2.Location = new System.Drawing.Point(168, 48);<br />this.richTextBox2.Name = "-";<br />this.richTextBox2.Size = new System.Drawing.Size(176, 96);<br />this.richTextBox2.TabIndex = 1;<br />this.richTextBox2.Text = "-";<br />//<br />// Form1<br />//<br />this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);<br />this.ClientSize = new System.Drawing.Size(352, 150);<br />this.Controls.Add(this.richTextBox1);<br />this.Controls.Add(this.button1);<br />this.Controls.Add(this.richTextBox2);<br />this.Name = "Form1";<br />this.Text = "Form1";<br />this.ResumeLayout(false);<br />}<br />#endregion<br /><br />/// <summary><br />/// The main entry point for the application.<br />/// </summary><br />[STAThread]<br />static void Main()<br />{<br />Application.Run(new Form1());<br />}<br /><br />/// <summary><br />/// This is the main method here we call the web pages and extract method<br />/// </summary><br />/// <param name="sender"></param><br />/// <param name="e"></param><br />private void button1_Click(object sender, System.EventArgs e)<br />{<br />System.Net.HttpWebRequest r ;<br />string strRes;<br />int count =0;<br />string [] nbmin ;<br /><br />//I found this regular expression which work well for RATP's real time bus position web site<br />// You will have to change it regarding the information you want to check.<br />Regex re = new Regex(">(?'1'[0-9]+ mn).*<", RegexOptions.IgnoreCaseRegexOptions.Compiled); // URL with rich querystrings RATP users will pay attention to "ligne" , "dir", standig for direction , "arr" standing for "arret" (los "libdir" and "lib arr") string URL1 ="http://www.ratp.info/horaires/index.php?reseau=BUS&etape=prec_bustram_ssotr&amp;ligne=179&libligne=GARE+DE+ROBINSON+%2F+PONT+DE+SEVRES&amp;dem=dem3&libarr=LA+BOURSIDIERE&amp;libdir=GARE+DE+ROBINSON&act=act_valid&amp;amp;amp;arr=179_5206_5436&dir=A"; string URL2 = "http://www.ratp.info/horaires/index.php?reseau=BUS&etape=prec_bustram_ssotr&amp;ligne=179&libligne=GARE+DE+ROBINSON+%2F+PONT+DE+SEVRES&amp;dem=dem3&libarr=LA+BOURSIDIERE&amp;libdir=PONT+DE+SEVRES&act=act_valid&amp;amp;amp;arr=179_5206_5436&dir=R"; r =(HttpWebRequest)WebRequest.Create(URL1); r.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials ; System.Net.HttpWebResponse rp = (HttpWebResponse)r.GetResponse(); // Gets the stream associated with the response. Stream receiveStream = rp.GetResponseStream(); Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); // Pipes the stream to a higher level stream reader with the required encoding format. StreamReader readStream = new StreamReader( receiveStream, encode ); Char[] read = new Char[256]; // Reads 256 characters at a time. count = readStream.Read( read, 0, 256 ); strRes =""; while (count > 0)<br />{<br />// Dumps the 256 characters on a string .<br />String str = new String(read,0, count);<br />strRes +=str;<br />count = readStream.Read(read, 0, 256);<br />}<br />// Releases the resources of the response.<br />rp.Close();<br />// Releases the resources of the Stream.<br />readStream.Close();<br /><br />//write the result of the extraction<br />this.richTextBox1.Text = "Bus 179 en direction de Robinson" + String.Join("\n", extractReg(strRes,re));<br /><br />strRes ="";<br />r.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials ;<br />r =(HttpWebRequest)WebRequest.Create(URL2);<br />r.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials ;<br />rp = (HttpWebResponse)r.GetResponse();<br /><br />count =0;<br />// Gets the stream associated with the response.<br />receiveStream = rp.GetResponseStream();<br />encode = System.Text.Encoding.GetEncoding("utf-8");<br />// Pipes the stream to a higher level stream reader with the required encoding format.<br />readStream = new StreamReader( receiveStream, encode );<br />read = new Char[256];<br />// Reads 256 characters at a time.<br />count = readStream.Read( read, 0, 256 );<br /><br />while (count > 0)<br />{<br />// Dumps the 256 characters on a string .<br />String str = new String(read,0, count);<br />strRes +=str;<br />count = readStream.Read(read, 0, 256);<br />}<br />// Releases the resources of the response.<br />rp.Close();<br />// Releases the resources of the Stream.<br />readStream.Close();<br /><br />re = new Regex(">(?'1'[0-9]+ mn).*<", RegexOptions.IgnoreCaseRegexOptions.Compiled); //write the result this.richTextBox2.Text = "Bus 179 en direction de pont de Sèvres " + String.Join("\n", extractReg(strRes,re)); } } } </tt>Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1140016196617299662006-02-15T06:58:00.000-08:002007-04-02T12:38:42.606-07:00ThanksHi everybody. <br /><br />I didn’t post for a long time on this blog, sorry about this. Today I'm going to take the time to do something:<br /><br />A quick ”Hello” to Stéphane, Eric, Eric (yes), Sophiane, Lucky (yes again), Bulent, Thierry, Christophe, Laurent, Fabienne, Sophianne, Michel and Nathalie. I worked with these guys and girls mainly on Oracle and Microsoft technologies for about three years. We made great things together. <br /><br />Thanks for everything.Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1134739395394929262005-12-16T05:23:00.000-08:002006-01-16T20:33:45.750-08:00googled2cd966929769ab9This is what google asked me to put on the sitemap featureMarcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1133540899988335702005-12-02T08:04:00.000-08:002006-01-19T20:36:48.430-08:00two lines in the datagrid headerOk, this is a dirty workaround but it works. <br /><br />In a winform datagrid you can't directly change the columns header height. is is the workaroun Eric, a collegue of mine find somewhere on internet : change the datagrid header font size without changing the column header font. <br /><br />for instance <br /> System.Drawing.Font f =new System.Drawing.Font("Verdana", <b>15.25F</b>, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point,Convert.ToByte(0));<br /><br /> MyDatagrid.HeaderFont = f;Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1127323879180124322005-09-21T10:30:00.000-07:002007-01-22T13:42:09.250-08:00Context saving with persistent datasets<i>This article propose a way to use dataset to make persistent an arbitrary set of data.in the context of a winform application</i><br /><br />Sometimes you need to stored datas but you don't think a database is the right way. <br />For instance if you want to store the user's context (search criterias,options, the last time he use the application...) in order to set it back the next time the application is used, you need a specific tool. <br />To achieve this you may use a little xml file. <br />But, most of the time, you don't know exactly what you will need to store in advance. <br />So defining and changing and changing again the schema of the xml file could be something close to a good headache.<br /><br />An idea is to propose a set of methods which adapt the schema inline. <br /><br />The microsoft .Net DataSet object has two powerfull methods ReadXml and WriteXml. <br />These methods manipulates the datas and also the schema of the dataset.<br />So I choose this object to implement my context saving class for winform application.<br />(It could be easily adapt for a server side use) <br /><br />The idea is that when a coder need a new persistent data, he use the following syntax:<br /><br />Contexte.getSimpleval("MyDataName");<br />The schema will be changed at the first use and the next time, it will bring back the last setled value.<br /><br />When modified, the data is stored like this:<br />Contexte.setSimpleval("MyNewinformationName", MyStringValue);// the stored info are here of string type<br /><br />If the amount of information is important data could be sort by collections using the syntaxes:<br /><br />getVal(string "MyNewCollectionName","MyNewinformationName")<br />and <br />setVal(string "MyNewCollectionName","MyNewinformationName", MyStringValue)<br /><br />The "save()" and "load()" methods are called at the begining and at the end of the application. <br />(typically the onLoad and onClose events of the main window). <br /> <br />Here is the code of the class, please critisize, comment and ask questions!<br /> <br /><font face = "courrier"><b><br />using System;<br />using System.Data;<br />using System.IO;<br /><br />namespace MyNamespace<br />{<br /> /// &lt;summary&gt;<br /> /// The Contexte class is used to make datas persistant<br /> /// Marc Boizeau<br /> /// Two types of data are managed<br /> /// - collections: values identified by a collection name and a field name<br /> /// - Simple values just identified by a name <br /> /// &lt;/summary&gt;<br /> public class Contexte<br /> {<br /> private const string FILE_NAME="Context.xml";<br /> // context data container dataset<br /> static private DataSet ds;<br /><br /> public Contexte()<br /> {<br /> }<br /><br /> /// &lt;summary&gt;<br /> /// Retrives the good path for context <br /> /// &lt;/summary&gt;<br /> /// &lt;returns&gt; the context path, string &lt;/returns&gt;<br /> static private string getFilePath()<br /> {<br /> //to change <br /> string path= Environment.GetEnvironmentVariable("APPDATA")+"/MyApplication/";<br /> <br /> if (!Directory.Exists(path))<br /> Directory.CreateDirectory(path);<br /> <br /> <br /> path+=FILE_NAME;<br /><br /> return path ;<br /> <br /> }<br /> //load the dataset with the xml file <br /> public static void load()<br /> {<br /> if (ds!=null)<br /> ds = null;<br /> <br /> ds = new DataSet("ContexteExpertises");<br /> <br /> try<br /> {<br /> if (File.Exists(getFilePath()))<br /> ds.ReadXml( getFilePath(),XmlReadMode.ReadSchema);<br /> }<br /> catch(Exception e)<br /> {// files do <br /> }<br /><br /> }<br /> <br /> //save the datafile <br /> public static void Save()<br /> {<br /> if(ds== null)<br /> {<br /> ds =new DataSet("ContexteExpertises");<br /> }<br /> ds.WriteXml(getFilePath(),XmlWriteMode.WriteSchema);<br /> }<br /><br /> // retrieve a datatable by its name<br /> private static DataTable getTable(string TableName)<br /> {<br /> DataTable dt;<br /> if (!ds.Tables.Contains(TableName))<br /> {<br /> dt = new DataTable(TableName);<br /> dt.Columns.Add("NAME");<br /> dt.Columns.Add("VALUE");<br /> dt.Constraints.Add("PK",dt.Columns["NAME"],true);<br /> ds.Tables.Add(dt);<br /> }<br /> else<br /> dt = ds.Tables[TableName];<br /> return dt;<br /> }<br /> <br /> //retrieves a data by a table name and a field name<br /> public static string getVal(string TableName, string Entry)<br /> {<br /> DataTable dt;<br /> DataView dv;<br /> dt = getTable(TableName);<br /> dv = dt.DefaultView;<br /><br /> if (Entry==null)<br /> Entry=""; <br /><br /> dv.RowFilter= " NAME ='" + Entry+ "'";<br /> //test if exists<br /> if (dv.Count==0)<br /> {//if not creates<br /> DataRow dr =dt.NewRow();<br /> dr["NAME"]= Entry;<br /> dr["VALUE"]="";<br /> dt.Rows.Add(dr);<br /> }<br /> //at this point the entry exist<br /> return dt.Rows.Find(Entry)["VALUE"].ToString();<br /> }<br /><br /><br /> // setting a data<br /> public static void setVal(string TableName, string Entry,string Val)<br /> {<br /> DataTable dt;<br /> DataView dv;<br /> dt = getTable(TableName);<br /> dv = dt.DefaultView;<br /> dv.RowFilter= " NAME ='" + Entry+ "'";<br /> <br /> if (Entry==null)<br /> Entry="";<br /> <br /> if (Val==null)<br /> Val="";<br /><br /> //test if exists<br /> if (dv.Count==0)<br /> {//if not creates<br /> DataRow dr =dt.NewRow();<br /> dr["NAME"]= Entry;<br /> dr["VALUE"]= "";<br /> dt.Rows.Add(dr);<br /> }<br /> //at this point the entry exists<br /> dt.Rows.Find(Entry)["VALUE"]=Val;<br /> }<br /> <br /> /// &lt;summary&gt;<br /> /// retrieves a simple value<br /> /// &lt;/summary&gt;<br /> /// &lt;param name="Entry"&gt;&lt;/param&gt;<br /> /// &lt;returns&gt;&lt;/returns&gt;<br /> public static string getSimpleVal(string Entry)<br /> {<br /> if (ds==null)<br /> load();<br /> return getVal("SIMPLE", Entry);<br /> }<br /><br /> /// &lt;summary&gt;<br /> /// set a simple value<br /> /// &lt;/summary&gt;<br /> /// &lt;param name="Entry"&gt;&lt;/param&gt;<br /> /// &lt;returns&gt;&lt;/returns&gt;<br /> public static void setSimpleVal(string Entry,string val)<br /> {<br /> if (ds==null)<br /> load();<br /> setVal("SIMPLE", Entry,val);<br /> }<br /><br /> <br /><br /> }<br />}<br /></b></font>Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1125421385911986222005-08-30T09:59:00.000-07:002005-10-14T04:00:59.890-07:00.net webservice sessionMaybe it is obvious but I've seen the question on a forum;<br />Q:"How to make the session collection work for a .net webservice like for asp.net? "<br /><br />A:"Just put the following before the web method:"<br /><font face = courrier>[ WebMethod(Description="Desc",EnableSession=true)]</font><br /><br />thats all folks!<br /><br />hope this helps.<br /><br />comments are welcome<br /><br /><br />Ok I've posted this a few time ago. And it still works. But, the session collection is not a real session objectin this case. It is instanciate just before the web method call, but I never seen when it is uninstanciate. For instance the "end_session" event never fire! <br />Also, I experiment troubles while debuging an object stored in this collection for a web method. <br />So, use this the least you can and do not expect this to be a good equivalent to the session collection in classical ASP .Net.Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1125313767215270872005-08-29T03:55:00.000-07:002005-09-21T02:09:41.816-07:00Winform, Web Services & credentialJust a tip today. <br /><br />Last week I built a web service based application which needs a windows authentication. <br />The schema was:<br />A winform client <br />A group of IIS web services. <br />An oracle database (as alway on this blog lol)<br /><br />How could the winform client say to the web services. "Hey i'm a member of this windows network, my login is Jdoe, trust me"<br /><br />Ok, first I asked my favourite web administrator to configure my IIS application to not allow anonymous users. Exactly like for a classical ASPX application. <br /><br />Then I changed my web.config file, puting the line :<br />&lt;authentication mode="Windows" /&gt; <br /><br />Ok IIS was then fine to authenticate users. <br />but my Winform webservice client wasn't ready yet. <br /><br />In order to be "windowsly" authenticate a webservice client need to send credentials to the server. <br />The .net framework provide a secure and elegant way to to that:<br /><br /><font face="courrier"><br />using System;<br />using System.Net;<br />....<br /><br />MyService.MyWebMethod ws = new MyService.MyWebMethod();<br />ws.Credentials = <b>CredentialCache.DefaultCredentials</b>;<br />...<br /></font><br /><br />and it works ! <br />I was then able to retrieve informations about my connected users. For instance<br />the login :<br /><font face="courrier"><br />...<br />strlogin = user.identity.name<br />...<br /></font><br /><br />that's all folks! <br />hope this helps!<br />Comments are welcome!Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1124458450285522432005-08-19T06:32:00.000-07:002005-08-22T11:06:24.366-07:00back to workHello everybody<br /><br />I'm back to work! I didn't post these last three weeks because I was <br /><a href="http://stranddjerba.freeservers.com/Location.html" target="site">here</a> and also <a href="http://www.edreams.es/edreams/espanol/packages/imageview.jhtml;$sessionid$3MU15LANNYC2LQFIS1WBNWWUVLR4QIV0?image=%2Fimages%2Fgallery%2F4405%2F2_Tunez_KsarGuilane_Desert01.jpg&title=Los+mejores+puertos+del+Mediterr%E1neo&back=%2Fedreams%2Fespanol%2Fso%2Fdettagli%2Fdettagli2.jhtml" target="site"> there</a> ,I also went to <a href="http://cm1cm2.ceyreste.free.fr/calanques.html"> this place</a> .Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1120836297818290412005-07-08T08:24:00.000-07:002005-07-08T08:24:57.823-07:00just a link<a title="blog directory" href="http://www.wilsdomain.com/"><b>Blog Directory</b></a><br /><br /><a title="search for blogs" href="http://www.juaxoo.com/"><b>Search for Blogs</b></a>Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1119631566411935422005-06-24T09:42:00.000-07:002007-02-20T13:44:19.883-08:00self descriptionSomebody ask for the code of the self descripting c# code i've done <a href="http://oraclevsmicrosoft.blogspot.com/2005/01/code-generation-and-self-description.html"> a few times ago here</a> it is :<br /><br /><font face="courier"><br />using System;<br />using System.Collections;<br />using System.ComponentModel;<br />using System.Windows.Forms;<br />using System.CodeDom;<br />using System.CodeDom.Compiler;<br />using Microsoft.CSharp;<br />using System.Collections.Specialized;<br />namespace WindowsApplication2<br />{<br /> /// Main form<br /><br /> public class Form1 : System.Windows.Forms.Form<br /> {<br /> private System.Windows.Forms.Button button2;<br /> private System.Windows.Forms.Button button1;<br /> private System.Windows.Forms.Button bt_itself;<br /> private System.Windows.Forms.RichTextBox rt1;<br /> private System.Windows.Forms.ListBox listBox1;<br /> private System.ComponentModel.Container components = null;<br /><br /> public Form1()<br /> {<br /> //<br /> // Requis pour la prise en charge du Concepteur Windows Forms<br /> //<br /> InitializeComponent();<br /> }<br /><br /> /// Nettoyage des ressources utilisées.<br /> protected override void Dispose( bool disposing )<br /> {<br /> if( disposing )<br /> {<br /> if (components != null)<br /> {<br /> components.Dispose();<br /> }<br /> }<br /> base.Dispose( disposing );<br /> }<br /><br /> #region Code généré par le Concepteur Windows Form<br /> /// &lt;summary&gt;<br /> /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas<br /> /// le contenu de cette méthode avec l'éditeur de code.<br /> /// &lt;/summary&gt;<br /> private void InitializeComponent() {<br /> this.listBox1 = new System.Windows.Forms.ListBox();<br /> this.rt1 = new System.Windows.Forms.RichTextBox();<br /> this.bt_itself = new System.Windows.Forms.Button();<br /> this.button1 = new System.Windows.Forms.Button();<br /> this.button2 = new System.Windows.Forms.Button();<br /> this.SuspendLayout();<br /> // <br /> // listBox1<br /> // <br /> this.listBox1.Location = new System.Drawing.Point(24, 360);<br /> this.listBox1.Name = &quot;listBox1&quot;;<br /> this.listBox1.Size = new System.Drawing.Size(1016, 108);<br /> this.listBox1.TabIndex = 3;<br /> // <br /> // rt1<br /> // <br /> this.rt1.Location = new System.Drawing.Point(24, 16);<br /> this.rt1.Name = &quot;rt1&quot;;<br /> this.rt1.Size = new System.Drawing.Size(632, 328);<br /> this.rt1.TabIndex = 1;<br /> this.rt1.Text = &quot;richTextBox1&quot;;<br /> // <br /> // bt_itself<br /> // <br /> this.bt_itself.Location = new System.Drawing.Point(696, 40);<br /> this.bt_itself.Name = &quot;bt_itself&quot;;<br /> this.bt_itself.Size = new System.Drawing.Size(72, 24);<br /> this.bt_itself.TabIndex = 0;<br /> this.bt_itself.Text = &quot;it self&quot;;<br /> this.bt_itself.Click += new System.EventHandler(this.bt_itself_Click);<br /> // <br /> // button1<br /> // <br /> this.button1.Location = new System.Drawing.Point(696, 8);<br /> this.button1.Name = &quot;button1&quot;;<br /> this.button1.Size = new System.Drawing.Size(72, 24);<br /> this.button1.TabIndex = 0;<br /> this.button1.Text = &quot;genere&quot;;<br /> this.button1.Click += new System.EventHandler(this.button1_Click);<br /> // <br /> // button2<br /> // <br /> this.button2.Location = new System.Drawing.Point(696, 72);<br /> this.button2.Name = &quot;button2&quot;;<br /> this.button2.Size = new System.Drawing.Size(72, 24);<br /> this.button2.TabIndex = 4;<br /> this.button2.Text = &quot;compile&quot;;<br /> this.button2.Click += new System.EventHandler(this.button2_Click);<br /> <br /> // <br /> // Form1<br /> // <br /> this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);<br /> this.ClientSize = new System.Drawing.Size(1032, 526);<br /> this.Controls.Add(this.button2);<br /> this.Controls.Add(this.listBox1);<br /> this.Controls.Add(this.rt1);<br /> this.Controls.Add(this.button1);<br /> this.Controls.Add(this.bt_itself);<br /> this.Name = &quot;Form1&quot;;<br /> this.Text = &quot;Form1&quot;;<br /> this.Load += new System.EventHandler(this.Form1_Load);<br /> this.ResumeLayout(false);<br /> }<br /> #endregion<br /><br /> /// Point d'entrée principal de l'application.<br /> [STAThread]<br /> static void Main()<br /> {<br /> Application.Run(new Form1());<br /> }<br />// methode de base <br /> string join(string[] arr,string sep)<br /> {string strReturn=&quot;&quot; ;<br /> foreach (string elt in arr)<br /> strReturn += elt+sep;<br /> strReturn.Substring(0,strReturn.Length-sep.Length);<br /> <br /> return strReturn;<br /> }<br /><br /> void seekandreplace(string[] arr,string strSrc,string strReplace)<br /> {<br /> int i=0;<br /> for(i=0;i&lt;=arr.Length-1;i++)<br /> { if(arr[i]==strSrc)<br /> arr[i]=strReplace;<br /> }<br /> }<br /> string format (string str)<br /> {<br /> str = str.Replace(&quot;\\&quot;,&quot;\\\\&quot;);<br /> str = str.Replace(&quot;\&quot;&quot;,&quot;\\\&quot;&quot;);<br /> return str; <br /> }<br /> string joinformat(string[] arr,string sep)<br /> {<br /> string strReturn= &quot;&quot; ;<br /> foreach (string elt in arr)<br /> { strReturn +=format( elt)+sep;}<br /> <br /> strReturn = strReturn.Substring( 0,strReturn.Length-sep.Length);<br /> <br /> return strReturn;<br /> }<br /> private void Form1_Load(object sender, System.EventArgs e)<br /> {<br /> //nothing special here <br /> }<br /><br /> private void button1_Click(object sender, System.EventArgs e)<br /> {// here is starting the main part of the code:<br /> //<br /> //the CodeCompileUnit is the abstract code structure:<br /><br /> // Create a new CodeCompileUnit to contain the program graph<br /> CodeCompileUnit CompileUnit = new CodeCompileUnit();<br /> // Declare a new namespace called Samples.<br /> CodeNamespace Samples = new CodeNamespace(&quot;Samples&quot;);<br /> // Add the new namespace to the compile unit.<br /> CompileUnit.Namespaces.Add( Samples );<br /><br /> // Add the new namespace import for the System namespace.<br /> Samples.Imports.Add( new CodeNamespaceImport(&quot;System&quot;) );<br /><br /> // Declare a new type called Class1.<br /> CodeTypeDeclaration Class1 = new CodeTypeDeclaration(&quot;echo&quot;);<br /> // Add the new type to the namespace's type collection.<br /> Samples.Types.Add(Class1);<br /><br /> //a variable declaration<br /> CodeVariableDeclarationStatement Var = new<br /> CodeVariableDeclarationStatement(&quot;System.String&quot;,&quot;str1&quot;);<br /> // Declare a new code entry point method<br /> CodeEntryPointMethod Start = new CodeEntryPointMethod();<br /> // Create a new method invocation expression.<br /> CodeMethodInvokeExpression cs1 =<br /> new CodeMethodInvokeExpression(<br /> // Call the System.Console.WriteLine method.<br /> <br /> new CodeTypeReferenceExpression(&quot;System.Console&quot;), &quot;ReadLine&quot;);<br /> CodeAssignStatement as1 = new CodeAssignStatement(<br /> new CodeVariableReferenceExpression(&quot;str1&quot;),cs1);<br /><br /> // Create a new method invocation expression.<br /> CodeMethodInvokeExpression cs2 =<br /> new CodeMethodInvokeExpression(<br /> // Call the System.Console.WriteLine method.<br /> new CodeTypeReferenceExpression(&quot;System.Console&quot;), &quot;WriteLine&quot;);<br /> cs2.Parameters.Add(new CodeVariableReferenceExpression(Var.Name));<br /><br /> Start.Statements.Add(Var);<br /> // Add the new method code statement.<br /> Start.Statements.Add( as1);<br /> // Add the new method code statement.<br /> Start.Statements.Add(new CodeExpressionStatement(cs2));<br /><br /> // Add the code entry point method to the type's members collection<br /> Class1.Members.Add( Start );<br /><br /><br /> System.IO.StringWriter Sw = new System.IO.StringWriter();<br /><br /> <br /> Microsoft.CSharp.CSharpCodeProvider provider =<br /> new CSharpCodeProvider();<br /> System.CodeDom.Compiler.ICodeGenerator generator = provider.CreateGenerator(Sw);<br /> CodeGeneratorOptions genOptions = new CodeGeneratorOptions();<br /><br /> // The code generator should insert blank lines <br /> genOptions.BlankLinesBetweenMembers = true;<br /><br /> try<br /> {<br /> generator.GenerateCodeFromCompileUnit(CompileUnit,Sw,genOptions);<br /> }<br /> catch (Exception Exc)<br /> {<br /> System.Windows.Forms.MessageBox.Show (Exc.Message);<br /> }<br /> rt1.Text = Sw.ToString();<br /><br /> }<br /> <br /> private void button2_Click(object sender, System.EventArgs e)<br /> {<br /> Microsoft.CSharp.CSharpCodeProvider provider =<br /> new CSharpCodeProvider();<br /> ///<br />// Compilation <br /> //instanciate csharp compiler<br /> System.CodeDom.Compiler.ICodeCompiler MyCompiler = provider.CreateCompiler();<br /> System.CodeDom.Compiler.CompilerParameters cp = new CompilerParameters();<br /> cp.GenerateExecutable = true;<br /> cp.CompilerOptions= &quot; /target:exe&quot;;<br /> cp.ReferencedAssemblies.AddRange( new string[]{&quot;System.Windows.Forms.dll&quot;,&quot;System.dll&quot;,&quot;System.drawing.dll&quot;,&quot;&quot;});<br /> //where your exe will be saved<br /> cp.OutputAssembly = &quot;c:\\echo.exe&quot;;<br /> // Invoke compilation.<br /> CompilerResults cr = MyCompiler.CompileAssemblyFromSource ( cp,rt1.Text);<br /> //<br /> // Return the results of compilation.<br /><br /> //eventually load compilation output to the listbox (usefull to debug)<br /> listBox1.DataSource=cr.Output;<br /><br /> //where is it? <br /> MessageBox.Show ( cr.PathToAssembly );<br /> }<br /><br /> private void bt_itself_Click(object sender, System.EventArgs e)<br /> {<br /> string[] arr=new string[]{<br />&quot;using System;&quot;,<br />&quot;using System.Collections;&quot;,<br />&quot;using System.ComponentModel;&quot;,<br />&quot;using System.Windows.Forms;&quot;,<br />&quot;using System.CodeDom;&quot;,<br />&quot;using System.CodeDom.Compiler;&quot;,<br />&quot;using Microsoft.CSharp;&quot;,<br />&quot;using System.Collections.Specialized;&quot;,<br />&quot;namespace WindowsApplication2&quot;,<br />&quot;{&quot;,<br />&quot; /// Main form&quot;,<br />&quot;&quot;,<br />&quot; public class Form1 : System.Windows.Forms.Form&quot;,<br />&quot; {&quot;,<br />&quot; private System.Windows.Forms.Button button2;&quot;,<br />&quot; private System.Windows.Forms.Button button1;&quot;,<br />&quot; private System.Windows.Forms.Button bt_itself;&quot;,<br />&quot; private System.Windows.Forms.RichTextBox rt1;&quot;,<br />&quot; private System.Windows.Forms.ListBox listBox1;&quot;,<br />&quot; private System.ComponentModel.Container components = null;&quot;,<br />&quot;&quot;,<br />&quot; public Form1()&quot;,<br />&quot; {&quot;,<br />&quot; //&quot;,<br />&quot; // Requis pour la prise en charge du Concepteur Windows Forms&quot;,<br />&quot; //&quot;,<br />&quot; InitializeComponent();&quot;,<br />&quot; }&quot;,<br />&quot;&quot;,<br />&quot; /// Nettoyage des ressources utilisées.&quot;,<br />&quot; protected override void Dispose( bool disposing )&quot;,<br />&quot; {&quot;,<br />&quot; if( disposing )&quot;,<br />&quot; {&quot;,<br />&quot; if (components != null)&quot;,<br />&quot; {&quot;,<br />&quot; components.Dispose();&quot;,<br />&quot; }&quot;,<br />&quot; }&quot;,<br />&quot; base.Dispose( disposing );&quot;,<br />&quot; }&quot;,<br />&quot;&quot;,<br />&quot; #region Code généré par le Concepteur Windows Form&quot;,<br />&quot; /// &lt;summary&gt;&quot;,<br />&quot; /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas&quot;,<br />&quot; /// le contenu de cette méthode avec l'éditeur de code.&quot;,<br />&quot; /// &lt;/summary&gt;&quot;,<br />&quot; private void InitializeComponent() {&quot;,<br />&quot; this.listBox1 = new System.Windows.Forms.ListBox();&quot;,<br />&quot; this.rt1 = new System.Windows.Forms.RichTextBox();&quot;,<br />&quot; this.bt_itself = new System.Windows.Forms.Button();&quot;,<br />&quot; this.button1 = new System.Windows.Forms.Button();&quot;,<br />&quot; this.button2 = new System.Windows.Forms.Button();&quot;,<br />&quot; this.SuspendLayout();&quot;,<br />&quot; // &quot;,<br />&quot; // listBox1&quot;,<br />&quot; // &quot;,<br />&quot; this.listBox1.Location = new System.Drawing.Point(24, 360);&quot;,<br />&quot; this.listBox1.Name = \&quot;listBox1\&quot;;&quot;,<br />&quot; this.listBox1.Size = new System.Drawing.Size(1016, 108);&quot;,<br />&quot; this.listBox1.TabIndex = 3;&quot;,<br />&quot; // &quot;,<br />&quot; // rt1&quot;,<br />&quot; // &quot;,<br />&quot; this.rt1.Location = new System.Drawing.Point(24, 16);&quot;,<br />&quot; this.rt1.Name = \&quot;rt1\&quot;;&quot;,<br />&quot; this.rt1.Size = new System.Drawing.Size(632, 328);&quot;,<br />&quot; this.rt1.TabIndex = 1;&quot;,<br />&quot; this.rt1.Text = \&quot;richTextBox1\&quot;;&quot;,<br />&quot; // &quot;,<br />&quot; // bt_itself&quot;,<br />&quot; // &quot;,<br />&quot; this.bt_itself.Location = new System.Drawing.Point(696, 40);&quot;,<br />&quot; this.bt_itself.Name = \&quot;bt_itself\&quot;;&quot;,<br />&quot; this.bt_itself.Size = new System.Drawing.Size(72, 24);&quot;,<br />&quot; this.bt_itself.TabIndex = 0;&quot;,<br />&quot; this.bt_itself.Text = \&quot;it self\&quot;;&quot;,<br />&quot; this.bt_itself.Click += new System.EventHandler(this.bt_itself_Click);&quot;,<br />&quot; // &quot;,<br />&quot; // button1&quot;,<br />&quot; // &quot;,<br />&quot; this.button1.Location = new System.Drawing.Point(696, 8);&quot;,<br />&quot; this.button1.Name = \&quot;button1\&quot;;&quot;,<br />&quot; this.button1.Size = new System.Drawing.Size(72, 24);&quot;,<br />&quot; this.button1.TabIndex = 0;&quot;,<br />&quot; this.button1.Text = \&quot;genere\&quot;;&quot;,<br />&quot; this.button1.Click += new System.EventHandler(this.button1_Click);&quot;,<br />&quot; // &quot;,<br />&quot; // button2&quot;,<br />&quot; // &quot;,<br />&quot; this.button2.Location = new System.Drawing.Point(696, 72);&quot;,<br />&quot; this.button2.Name = \&quot;button2\&quot;;&quot;,<br />&quot; this.button2.Size = new System.Drawing.Size(72, 24);&quot;,<br />&quot; this.button2.TabIndex = 4;&quot;,<br />&quot; this.button2.Text = \&quot;compile\&quot;;&quot;,<br />&quot; this.button2.Click += new System.EventHandler(this.button2_Click);&quot;,<br />&quot; &quot;,<br />&quot; // &quot;,<br />&quot; // Form1&quot;,<br />&quot; // &quot;,<br />&quot; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);&quot;,<br />&quot; this.ClientSize = new System.Drawing.Size(1032, 526);&quot;,<br />&quot; this.Controls.Add(this.button2);&quot;,<br />&quot; this.Controls.Add(this.listBox1);&quot;,<br />&quot; this.Controls.Add(this.rt1);&quot;,<br />&quot; this.Controls.Add(this.button1);&quot;,<br />&quot; this.Controls.Add(this.bt_itself);&quot;,<br />&quot; this.Name = \&quot;Form1\&quot;;&quot;,<br />&quot; this.Text = \&quot;Form1\&quot;;&quot;,<br />&quot; this.Load += new System.EventHandler(this.Form1_Load);&quot;,<br />&quot; this.ResumeLayout(false);&quot;,<br />&quot; }&quot;,<br />&quot; #endregion&quot;,<br />&quot;&quot;,<br />&quot; /// Point d'entrée principal de l'application.&quot;,<br />&quot; [STAThread]&quot;,<br />&quot; static void Main()&quot;,<br />&quot; {&quot;,<br />&quot; Application.Run(new Form1());&quot;,<br />&quot; }&quot;,<br />&quot;// methode de base &quot;,<br />&quot; string join(string[] arr,string sep)&quot;,<br />&quot; {string strReturn=\&quot;\&quot; ;&quot;,<br />&quot; foreach (string elt in arr)&quot;,<br />&quot; strReturn += elt+sep;&quot;,<br />&quot; strReturn.Substring(0,strReturn.Length-sep.Length);&quot;,<br />&quot; &quot;,<br />&quot; return strReturn;&quot;,<br />&quot; }&quot;,<br />&quot;&quot;,<br />&quot; void seekandreplace(string[] arr,string strSrc,string strReplace)&quot;,<br />&quot; {&quot;,<br />&quot; int i=0;&quot;,<br />&quot; for(i=0;i&lt;=arr.Length-1;i++)&quot;,<br />&quot; { if(arr[i]==strSrc)&quot;,<br />&quot; arr[i]=strReplace;&quot;,<br />&quot; }&quot;,<br />&quot; }&quot;,<br />&quot; string format (string str)&quot;,<br />&quot; {&quot;,<br />&quot; str = str.Replace(\&quot;\\\\\&quot;,\&quot;\\\\\\\\\&quot;);&quot;,<br />&quot; str = str.Replace(\&quot;\\\&quot;\&quot;,\&quot;\\\\\\\&quot;\&quot;);&quot;,<br />&quot; return str; &quot;,<br />&quot; }&quot;,<br />&quot; string joinformat(string[] arr,string sep)&quot;,<br />&quot; {&quot;,<br />&quot; string strReturn= \&quot;\&quot; ;&quot;,<br />&quot; foreach (string elt in arr)&quot;,<br />&quot; { strReturn +=format( elt)+sep;}&quot;,<br />&quot; &quot;,<br />&quot; strReturn = strReturn.Substring( 0,strReturn.Length-sep.Length);&quot;,<br />&quot; &quot;,<br />&quot; return strReturn;&quot;,<br />&quot; }&quot;,<br />&quot; private void Form1_Load(object sender, System.EventArgs e)&quot;,<br />&quot; {&quot;,<br />&quot; //nothing special here &quot;,<br />&quot; }&quot;,<br />&quot;&quot;,<br />&quot; private void button1_Click(object sender, System.EventArgs e)&quot;,<br />&quot; {// here is starting the main part of the code:&quot;,<br />&quot; //&quot;,<br />&quot; //the CodeCompileUnit is the abstract code structure:&quot;,<br />&quot;&quot;,<br />&quot; // Create a new CodeCompileUnit to contain the program graph&quot;,<br />&quot; CodeCompileUnit CompileUnit = new CodeCompileUnit();&quot;,<br />&quot; // Declare a new namespace called Samples.&quot;,<br />&quot; CodeNamespace Samples = new CodeNamespace(\&quot;Samples\&quot;);&quot;,<br />&quot; // Add the new namespace to the compile unit.&quot;,<br />&quot; CompileUnit.Namespaces.Add( Samples );&quot;,<br />&quot;&quot;,<br />&quot; // Add the new namespace import for the System namespace.&quot;,<br />&quot; Samples.Imports.Add( new CodeNamespaceImport(\&quot;System\&quot;) );&quot;,<br />&quot;&quot;,<br />&quot; // Declare a new type called Class1.&quot;,<br />&quot; CodeTypeDeclaration Class1 = new CodeTypeDeclaration(\&quot;echo\&quot;);&quot;,<br />&quot; // Add the new type to the namespace's type collection.&quot;,<br />&quot; Samples.Types.Add(Class1);&quot;,<br />&quot;&quot;,<br />&quot; //a variable declaration&quot;,<br />&quot; CodeVariableDeclarationStatement Var = new&quot;,<br />&quot; CodeVariableDeclarationStatement(\&quot;System.String\&quot;,\&quot;str1\&quot;);&quot;,<br />&quot; // Declare a new code entry point method&quot;,<br />&quot; CodeEntryPointMethod Start = new CodeEntryPointMethod();&quot;,<br />&quot; // Create a new method invocation expression.&quot;,<br />&quot; CodeMethodInvokeExpression cs1 =&quot;,<br />&quot; new CodeMethodInvokeExpression(&quot;,<br />&quot; // Call the System.Console.WriteLine method.&quot;,<br />&quot; &quot;,<br />&quot; new CodeTypeReferenceExpression(\&quot;System.Console\&quot;), \&quot;ReadLine\&quot;);&quot;,<br />&quot; CodeAssignStatement as1 = new CodeAssignStatement(&quot;,<br />&quot; new CodeVariableReferenceExpression(\&quot;str1\&quot;),cs1);&quot;,<br />&quot;&quot;,<br />&quot; // Create a new method invocation expression.&quot;,<br />&quot; CodeMethodInvokeExpression cs2 =&quot;,<br />&quot; new CodeMethodInvokeExpression(&quot;,<br />&quot; // Call the System.Console.WriteLine method.&quot;,<br />&quot; new CodeTypeReferenceExpression(\&quot;System.Console\&quot;), \&quot;WriteLine\&quot;);&quot;,<br />&quot; cs2.Parameters.Add(new CodeVariableReferenceExpression(Var.Name));&quot;,<br />&quot;&quot;,<br />&quot; Start.Statements.Add(Var);&quot;,<br />&quot; // Add the new method code statement.&quot;,<br />&quot; Start.Statements.Add( as1);&quot;,<br />&quot; // Add the new method code statement.&quot;,<br />&quot; Start.Statements.Add(new CodeExpressionStatement(cs2));&quot;,<br />&quot;&quot;,<br />&quot; // Add the code entry point method to the type's members collection&quot;,<br />&quot; Class1.Members.Add( Start );&quot;,<br />&quot;&quot;,<br />&quot;&quot;,<br />&quot; System.IO.StringWriter Sw = new System.IO.StringWriter();&quot;,<br />&quot;&quot;,<br />&quot; &quot;,<br />&quot; Microsoft.CSharp.CSharpCodeProvider provider =&quot;,<br />&quot; new CSharpCodeProvider();&quot;,<br />&quot; System.CodeDom.Compiler.ICodeGenerator generator = provider.CreateGenerator(Sw);&quot;,<br />&quot; CodeGeneratorOptions genOptions = new CodeGeneratorOptions();&quot;,<br />&quot;&quot;,<br />&quot; // The code generator should insert blank lines &quot;,<br />&quot; genOptions.BlankLinesBetweenMembers = true;&quot;,<br />&quot;&quot;,<br />&quot; try&quot;,<br />&quot; {&quot;,<br />&quot; generator.GenerateCodeFromCompileUnit(CompileUnit,Sw,genOptions);&quot;,<br />&quot; }&quot;,<br />&quot; catch (Exception Exc)&quot;,<br />&quot; {&quot;,<br />&quot; System.Windows.Forms.MessageBox.Show (Exc.Message);&quot;,<br />&quot; }&quot;,<br />&quot; rt1.Text = Sw.ToString();&quot;,<br />&quot;&quot;,<br />&quot; }&quot;,<br />&quot; &quot;,<br />&quot; private void button2_Click(object sender, System.EventArgs e)&quot;,<br />&quot; {&quot;,<br />&quot; Microsoft.CSharp.CSharpCodeProvider provider =&quot;,<br />&quot; new CSharpCodeProvider();&quot;,<br />&quot; ///&quot;,<br />&quot;// Compilation &quot;,<br />&quot; //instanciate csharp compiler&quot;,<br />&quot; System.CodeDom.Compiler.ICodeCompiler MyCompiler = provider.CreateCompiler();&quot;,<br />&quot; System.CodeDom.Compiler.CompilerParameters cp = new CompilerParameters();&quot;,<br />&quot; cp.GenerateExecutable = true;&quot;,<br />&quot; cp.CompilerOptions= \&quot; /target:exe\&quot;;&quot;,<br />&quot; cp.ReferencedAssemblies.AddRange( new string[]{\&quot;System.Windows.Forms.dll\&quot;,\&quot;System.dll\&quot;,\&quot;System.drawing.dll\&quot;,\&quot;\&quot;});&quot;,<br />&quot; //where your exe will be saved&quot;,<br />&quot; cp.OutputAssembly = \&quot;c:\\\\echo.exe\&quot;;&quot;,<br />&quot; // Invoke compilation.&quot;,<br />&quot; CompilerResults cr = MyCompiler.CompileAssemblyFromSource ( cp,rt1.Text);&quot;,<br />&quot; //&quot;,<br />&quot; // Return the results of compilation.&quot;,<br />&quot;&quot;,<br />&quot; //eventually load compilation output to the listbox (usefull to debug)&quot;,<br />&quot; listBox1.DataSource=cr.Output;&quot;,<br />&quot;&quot;,<br />&quot; //where is it? &quot;,<br />&quot; MessageBox.Show ( cr.PathToAssembly );&quot;,<br />&quot; }&quot;,<br />&quot;&quot;,<br />&quot; private void bt_itself_Click(object sender, System.EventArgs e)&quot;,<br />&quot; {&quot;,<br />&quot; string[] arr=new string[]{&quot;,<br />&quot;Les sanglots longs des violons de l'automne bercent mon coeur d'une langueur monotone&quot;,<br />&quot; };&quot;,<br />&quot; seekandreplace(arr,\&quot;Les sanglots longs des violons de l'automne bercent mon coeur d'une langueur monotone\&quot;,\&quot;\\\&quot;\&quot;+joinformat(arr,\&quot;\\\&quot;,\\n\\\&quot;\&quot;)+\&quot;\\\&quot;\&quot;);&quot;,<br />&quot; this.rt1.Text = join(arr,\&quot;\\n\&quot;);&quot;,<br />&quot; }&quot;,<br />&quot; }&quot;,<br />&quot;}&quot;<br /> };<br /> seekandreplace(arr,&quot;Les sanglots longs des violons de l'automne bercent mon coeur d'une langueur monotone&quot;,&quot;\&quot;&quot;+joinformat(arr,&quot;\&quot;,\n\&quot;&quot;)+&quot;\&quot;&quot;);<br /> this.rt1.Text = join(arr,&quot;\n&quot;);<br /> }<br /> }<br />}<br /><br /><br /></font>Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1119011034433748662005-06-17T05:21:00.000-07:002007-03-16T14:41:56.263-07:00A web crawler(regular expressions and httprequest)Hello everybody, i'm back to the blog!<br /><br />Today I'd like to demonstrate two powerfull features of the .net Framework: the httpWebrequest/httWebResponse and the RegEx object. I will then propose an implementation of a mini Web Crawler.<br /><br />httpWebrequest and httWebResponse are both object of the System.Net namespace. <br />With this objects, retrieving a text stream from a URI is as easy as this:<br /><br /><font face = "courier"><b><br />// Creates an HttpWebRequest with the specified URL. <br />HttpWebRequest myHttpWebRequest;<br /> <br />myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strURL); <br /> <br />// Sends the HttpWebRequest and waits for the response. <br />HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); <br />// Gets the stream associated with the response.<br />Stream receiveStream = myHttpWebResponse.GetResponseStream();<br />Encoding encode = System.Text.Encoding.GetEncoding("utf-8");<br />// Pipes the stream to a higher level stream reader with the required encoding format. <br />StreamReader readStream = new StreamReader( receiveStream, encode );<br />Char[] read = new Char[256];<br />// Reads 256 characters at a time. <br />int count = readStream.Read( read, 0, 256 );<br /> <br />while (count > 0) <br />{<br /> // Dumps the 256 characters on a string .<br /> String str = new String(read,0, count);<br /> strRes +=str;<br /> count = readStream.Read(read, 0, 256);<br />}<br />// Releases the resources of the response.<br />myHttpWebResponse.Close();<br />// Releases the resources of the Stream.<br />readStream.Close(); <br /></b></font><br /><br />The regEx object is the .net implementation for regular expressions. If you don't know what it is just remember it's the best way to perform text analysis. <br />For instance here is a function which retrieves in an array the "href"s in a web page. <br /><br /><font face = "courier"><b><br /> private string [] extractURIS(string strHTML)<br /> {<br /> Match m;<br /><br /> String[] results = new String[101];<br /> <br /> <br /> // Create a new Regex object and define the regular expression.<br /> Regex r = new Regex(<font color="blue">"href\\s*=\\s*(?:\"(?'1'[^\"]*)\"|(?'1'\\S+)).*>"</font>,<br /> RegexOptions.IgnoreCase|RegexOptions.Compiled);<br /><br /> // Use the Matches method to find all matches in the input string.<br /> // Loop through the match collection to retrieve all <br /> // matches.<br /> int i=0;<br /> m = r.Match(strHTML);<br /> <br /> for (i=0; (m.Success && i&lt;100); m = m.NextMatch()) <br /> {i++;<br /><br /> // Add the match string to the string array. <br /> results[i] = m.Groups[1].ToString() ;<br /> <br /> }<br /> return results;<br /> }<br /></b><br /></font><br /><br />OK, have a great breath and look at this<br />"href\\s*=\\s*(?:\"(?'1'[^\"]*)\"|(?'1'\\S+)).*&gt;"<br />let's decrypt this regular expression . <br />"href" just mean that the patern is preceded by the word "href"<br />\\s stands for "any space character" <br />\\s* stands for "a 0 or n space character"<br />so the first part of the regEx :"href\\s*=\\s*" mean that the pattern we are looking for begins by "href" then spaces, then the "=" character and then spaces. <br /><br />[^\"] means "everything but a double quote character" (the \ is here to say " isnt a special character of the RegEx)<br />so [^\"]* is a succession of 0 or n character whithout any double quote<br /><br />(?'1'......) means that whe give the name '1' to the .... expression <br />Here we use it two times in the subexpression:<br />\"(?'1'[^\"]*)\"|(?'1'\\S+) <br />knowing that "|" is a logicall OR, you can guess that '1' is either <br />a succession of "without double quote" between two double quotes or "a succession of at least one non spaces characters"(\\S+)<br /><br />(?:....) just propagate the subexpression to the top level .<br /> <br />a dot (.) means "any character"<br />so:<br />.*&gt; means that our regEx ends with a succession of any character an then a "&gt;"<br /><br />wow... <br />for further info have a look to : http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconregularexpressionslanguageelements.asp<br /><br /><br />So lets use it in our little web crawler. <br /><br />To compile the following , save it with a ".cs" extension and use the csc.exe of your framework installation, for instance use the following:<br />C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\csc.exe /target:winexe /recurse:*.*<br />int the cs directory. <br /><br /><font face="courier"><b><br />using System;<br />using System.Drawing;<br />using System.Collections;<br />using System.ComponentModel;<br />using System.Windows.Forms;<br />using System.Data;<br />using System.Net;<br />using System.IO;<br />using System.Web;<br />using System.Text;<br />using System.Text.RegularExpressions;<br />using System.Collections.Specialized;<br /><br />namespace webrequest<br />{<br />/// &lt;summary&gt;<br />/// Description résumée de Form1.<br />/// &lt;/summary&gt;<br />public class WebCrawler : System.Windows.Forms.Form<br />{<br />private System.Windows.Forms.Button btLoad;<br />private System.Windows.Forms.TextBox tbURI;<br />private System.Windows.Forms.RichTextBox rtbHTML;<br />private System.Windows.Forms.RichTextBox rtbLOg;<br /><br />private string MainString;<br />private StringDictionary dicURL;<br />private System.Windows.Forms.Label label1;<br />private System.Windows.Forms.Label label2;<br />private System.Windows.Forms.TextBox tbiProf;<br />private System.Windows.Forms.TextBox tbMax;<br />private System.Windows.Forms.Label label3; <br />/// &lt;summary&gt;<br />/// Variable nécessaire au concepteur.<br />/// &lt;/summary&gt;<br />private System.ComponentModel.Container components = null;<br /><br />public WebCrawler()<br />{<br /> dicURL = new StringDictionary();<br /> //<br /> // Requis pour la prise en charge du Concepteur Windows Forms<br /> //<br /> InitializeComponent();<br /><br /> //<br /> // TODO : ajoutez le code du constructeur après l'appel à InitializeComponent<br /> //<br />}<br /><br />/// &lt;summary&gt;<br />/// Nettoyage des ressources utilisées.<br />/// &lt;/summary&gt;<br />protected override void Dispose( bool disposing )<br />{<br /> if( disposing )<br /> {<br /> if (components != null) <br /> {<br /> components.Dispose();<br /> }<br /> }<br /> base.Dispose( disposing );<br />}<br /><br />#region Code généré par le Concepteur Windows Form<br />/// &lt;summary&gt;<br />/// Méthode requise pour la prise en charge du concepteur - ne modifiez pas<br />/// le contenu de cette méthode avec l'éditeur de code.<br />/// &lt;/summary&gt;<br />private void InitializeComponent()<br />{<br /> this.btLoad = new System.Windows.Forms.Button();<br /> this.tbURI = new System.Windows.Forms.TextBox();<br /> this.rtbHTML = new System.Windows.Forms.RichTextBox();<br /> this.rtbLOg = new System.Windows.Forms.RichTextBox();<br /> this.tbiProf = new System.Windows.Forms.TextBox();<br /> this.label1 = new System.Windows.Forms.Label();<br /> this.label2 = new System.Windows.Forms.Label();<br /> this.tbMax = new System.Windows.Forms.TextBox();<br /> this.label3 = new System.Windows.Forms.Label();<br /> this.SuspendLayout();<br /> // <br /> // btLoad<br /> // <br /> this.btLoad.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) <br /> | System.Windows.Forms.AnchorStyles.Left) <br /> | System.Windows.Forms.AnchorStyles.Right)));<br /> this.btLoad.Location = new System.Drawing.Point(16, 112);<br /> this.btLoad.Name = "btLoad";<br /> this.btLoad.Size = new System.Drawing.Size(272, 120);<br /> this.btLoad.TabIndex = 0;<br /> this.btLoad.Text = "Crawl!";<br /> this.btLoad.Click += new System.EventHandler(this.btLoad_Click);<br /> // <br /> // tbURI<br /> // <br /> this.tbURI.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) <br /> | System.Windows.Forms.AnchorStyles.Right)));<br /> this.tbURI.Location = new System.Drawing.Point(120, 16);<br /> this.tbURI.Name = "tbURI";<br /> this.tbURI.Size = new System.Drawing.Size(712, 20);<br /> this.tbURI.TabIndex = 1;<br /> this.tbURI.Text = "http://oraclevsmicrosoft.blogspot.com";<br /> // <br /> // rtbHTML<br /> // <br /> this.rtbHTML.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) <br /> | System.Windows.Forms.AnchorStyles.Right)));<br /> this.rtbHTML.Location = new System.Drawing.Point(8, 248);<br /> this.rtbHTML.Name = "rtbHTML";<br /> this.rtbHTML.Size = new System.Drawing.Size(832, 136);<br /> this.rtbHTML.TabIndex = 2;<br /> this.rtbHTML.Text = "";<br /> // <br /> // rtbLOg<br /> // <br /> this.rtbLOg.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) <br /> | System.Windows.Forms.AnchorStyles.Right)));<br /> this.rtbLOg.Location = new System.Drawing.Point(297, 40);<br /> this.rtbLOg.Name = "rtbLOg";<br /> this.rtbLOg.Size = new System.Drawing.Size(536, 200);<br /> this.rtbLOg.TabIndex = 3;<br /> this.rtbLOg.Text = "";<br /> this.rtbLOg.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.rtbLOg_LinkClicked);<br /> // <br /> // tbiProf<br /> // <br /> this.tbiProf.Location = new System.Drawing.Point(120, 48);<br /> this.tbiProf.Name = "tbiProf";<br /> this.tbiProf.Size = new System.Drawing.Size(48, 20);<br /> this.tbiProf.TabIndex = 4;<br /> this.tbiProf.Text = "5";<br /> // <br /> // label1<br /> // <br /> this.label1.Location = new System.Drawing.Point(8, 16);<br /> this.label1.Name = "label1";<br /> this.label1.Size = new System.Drawing.Size(88, 16);<br /> this.label1.TabIndex = 5;<br /> this.label1.Text = "Starting URI";<br /> // <br /> // label2<br /> // <br /> this.label2.Location = new System.Drawing.Point(8, 48);<br /> this.label2.Name = "label2";<br /> this.label2.Size = new System.Drawing.Size(88, 16);<br /> this.label2.TabIndex = 6;<br /> this.label2.Text = "Max depht";<br /> // <br /> // tbMax<br /> // <br /> this.tbMax.Location = new System.Drawing.Point(120, 80);<br /> this.tbMax.Name = "tbMax";<br /> this.tbMax.Size = new System.Drawing.Size(104, 20);<br /> this.tbMax.TabIndex = 4;<br /> this.tbMax.Text = "1000";<br /> // <br /> // label3<br /> // <br /> this.label3.Location = new System.Drawing.Point(8, 88);<br /> this.label3.Name = "label3";<br /> this.label3.Size = new System.Drawing.Size(112, 16);<br /> this.label3.TabIndex = 6;<br /> this.label3.Text = "Max number of links";<br /> // <br /> // WebCrawler<br /> // <br /> this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);<br /> this.ClientSize = new System.Drawing.Size(848, 398);<br /> this.Controls.Add(this.label2);<br /> this.Controls.Add(this.label1);<br /> this.Controls.Add(this.tbiProf);<br /> this.Controls.Add(this.rtbLOg);<br /> this.Controls.Add(this.rtbHTML);<br /> this.Controls.Add(this.tbURI);<br /> this.Controls.Add(this.btLoad);<br /> this.Controls.Add(this.tbMax);<br /> this.Controls.Add(this.label3);<br /> this.MinimumSize = new System.Drawing.Size(856, 432);<br /> this.Name = "WebCrawler";<br /> this.Text = "Form1";<br /> this.ResumeLayout(false);<br /><br />}<br />#endregion<br /><br />/// &lt;summary&gt;<br />/// Point d'entrée principal de l'application.<br />/// &lt;/summary&gt;<br />[STAThread]<br />static void Main() <br />{<br /> Application.Run(new WebCrawler());<br />}<br /><br />// ne garde que le body du document et remplace toutes les balises par un espace simple<br />// enfin decode le html pour remplacer les énbsp; et autres<br />private string deleteTagg(string strHTML)<br />{<br /> Match m;<br /> string strRes ="";<br /> Regex r = new Regex ("&lt;body.*&gt;(.|\\n)*&lt;/body&gt;",<br /> RegexOptions.IgnoreCase);<br /> m = r.Match(strHTML); <br /> if (m.Success ) <br /> {<br /> strRes = m.Value;<br /> <br /> }<br /> r = null;<br /> r = new Regex ("&lt;(.|\\n)*?&gt;",<br /> RegexOptions.IgnoreCase);<br /> strRes = r.Replace(strRes," ");<br /><br /> strRes =HttpUtility.HtmlDecode(strRes);<br /><br /> return strRes ;<br />}<br />private string [] extractURIS(string strHTML)<br />{<br /> Match m;<br /><br /> String[] results = new String[101];<br /><br /><br /> // Create a new Regex object and define the regular expression.<br /> Regex r = new Regex ("href\\s*=\\s*(?:\"(?'1'[^\"]*)\"|(?'1'\\S+)).*&gt;",<br /> RegexOptions.IgnoreCase|RegexOptions.Compiled);<br /><br /> // Use the Matches method to find all matches in the input string.<br /> // Loop through the match collection to retrieve all <br /> // matches.<br /> int i=0;<br /> m = r.Match(strHTML);<br /> <br /> for (i=0; (m.Success && i&lt;100); m = m.NextMatch()) <br /> {i++;<br /><br /> // Add the match string to the string array. <br /> results[i] = m.Groups[1].ToString() ;<br /><br /> }<br />return results;<br />}<br />private string loadUrl(string strURL)<br />{<br /> string strRes="" ; <br /> try <br /> {<br /> // Creates an HttpWebRequest with the specified URL. <br /> HttpWebRequest myHttpWebRequest;<br /> <br /> myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strURL); <br /> <br /> // Sends the HttpWebRequest and waits for the response. <br /> HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); <br /> // Gets the stream associated with the response.<br /> Stream receiveStream = myHttpWebResponse.GetResponseStream();<br /> Encoding encode = System.Text.Encoding.GetEncoding("utf-8");<br /> // Pipes the stream to a higher level stream reader with the required encoding format. <br /> StreamReader readStream = new StreamReader( receiveStream, encode );<br /> Char[] read = new Char[256];<br /> // Reads 256 characters at a time. <br /> int count = readStream.Read( read, 0, 256 );<br /> <br /> while (count &gt; 0) <br /> {<br /> // Dumps the 256 characters on a string .<br /> String str = new String(read,0, count);<br /> strRes +=str;<br /> count = readStream.Read(read, 0, 256);<br /> }<br /> // Releases the resources of the response.<br /> myHttpWebResponse.Close();<br /> // Releases the resources of the Stream.<br /> readStream.Close();<br /> <br /> }<br /><br /> catch(Exception exp)<br /> {<br /> rtbLOg.AppendText("error at URI : "+ strURL +"\n");<br /> strRes ="";<br /> }<br /> return strRes;<br />}<br /><br />private void btLoad_Click(object sender, System.EventArgs e)<br />{<br /> recure(tbURI.Text,Convert.ToInt16(tbiProf.Text));<br /> rtbLOg.AppendText(dicURL.Count.ToString ());<br />}<br />private void recure(string strURL,int ilevel)<br />{<br /> MainString="";<br /> Match m;<br /> <br /><br /> <br /><br /> if ((ilevel)&gt;0 )<br /> {<br /> <br /> MainString = loadUrl(strURL);<br /> <br /> if (dicURL.Count&lt;Convert.ToInt32(tbMax.Text))<br /> {<br /> // récuperation des URLS<br /> string []strArUris= extractURIS(MainString);<br /> for (int i=0; i&lt;strArUris.Length&&dicURL.Count&lt;Convert.ToInt32(tbMax.Text);i++)<br /> {<br /> if (strArUris[i]!=null)<br /> {<br /> // check that the URi begins with a http<br /> Regex r = new Regex ("http://.+",<br /> RegexOptions.IgnoreCase);<br /> m = r.Match(strArUris[i]); <br /> <br /> if (!dicURL.ContainsKey(strArUris[i])&& m.Success )<br /> {<br /> dicURL.Add(strArUris[i],"1");<br /> recure(strArUris[i],ilevel-1);<br /> rtbLOg.AppendText(strArUris[i]+" " +ilevel+"\n");<br /> <br /> }<br /> else<br /> dicURL[strArUris[i]]=Convert.ToString(Convert.ToInt32(dicURL[strArUris[i]])+1);<br /><br /> }<br /> }<br /> }<br /> //here could be a text flow extraction <br /> // rtbHTML.Text =deleteTagg(rtbHTML.Text);<br /> //rtbHTML.Text =deleteTagg("&lt;/body&gt;");<br /> }<br /> <br />}<br /><br />private void rtbLOg_LinkClicked(object sender, System.Windows.Forms.LinkClickedEventArgs e)<br />{<br /> //Launch in ie <br /> System.Diagnostics.Process.Start(e.LinkText);<br /> rtbHTML.Text= deleteTagg(loadUrl(e.LinkText));<br />}<br /><br />}<br />}<br /><br />Thats all folks! Hope this helps, comments are welcome. <br /><br /></b></font>Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1114674999299867662005-04-28T00:55:00.000-07:002005-04-28T00:56:39.300-07:00linkjust a link today:<br /><a href="http://www.dbforumz.com" target="_blank" title="Database Forums" alt="Database Forums">Database Forums</a>Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1113917116324475632005-04-19T06:23:00.000-07:002007-03-03T02:26:00.373-08:00call an Oracle stored proc with oledb .netThanks to Emilio who ask the question on microsoft.public.dotnet.framework.adonet newsgroup. <br /><br />here is a syntaxe I've just test :<br /><!-- code formatted by http://manoli.net/csharpformat/ --><br /><style type="text/css"> .csharpcode { font-size: 10pt; color: black; font-family: Courier New , Courier, Monospace; background-color: #ffffff; /*white-space: pre;*/ }<br /> .csharpcode pre { margin: 0px; }<br /> .rem { color: #008000; }<br /> .kwrd { color: #0000ff; }<br /> .str { color: #006080; }<br /> .op { color: #0000c0; }<br /> .preproc { color: #cc6633; }<br /> .asp { background-color: #ffff00; }<br /> .html { color: #800000; }<br /> .attr { color: #ff0000; }<br /> .alt { background-color: #f4f4f4; width: 100%; margin: 0px; }<br /> .lnum { color: #606060; }<br /></style><br /><pre class="csharpcode"><br /><span class="kwrd">this</span>.cmdInsertLib.CommandText = <span class="str">"MyStoredProc"</span>;<br /><span class="kwrd">this</span>.cmdInsertLib.CommandType = System.Data.CommandType.StoredProcedure;<br /><span class="kwrd">this</span>.cmdInsertLib.Parameters.Add(<span class="kwrd"><br /> new</span> System.Data.OleDb.OleDbParameter(<span class="str">"P1"</span>,<br /> System.Data.OleDb.OleDbType.VarWChar, 100));<br /><span class="kwrd">this</span>.cmdInsertLib.Parameters.Add(<span class="kwrd"><br /> new</span> System.Data.OleDb.OleDbParameter(<span class="str">"P2"</span>, <br /> System.Data.OleDb.OleDbType.VarWChar, 100));<br />cmdInsertLib.Parameters[0].Value = textBox1.Text.ToString();<br />cmdInsertLib.Parameters[1].Value = textBox2.Text.ToString();<br />cmdInsertLib.ExecuteNonQuery();</pre><br />that's all folks <br /><br />hope this helps<br /><br />comments are welcomeMarcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1112895573167375042005-04-07T10:10:00.000-07:002007-02-20T21:03:41.056-08:00Updating two lines with one data adapter.<div class="Section1"><br /><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">Datatables and dataAdapter are designed to manipulate one database table at a time. The idea is that dataTable is like an asynchronous part of the database. So, when you make a change on one row of the dataTable you are suppose to change one and only one row in the database's table when synchronizing. Of course, sometimes it is not what you would like to do. </span></p><br /><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">Today I would like to demonstrate how to update multiple rows in an Oracle table without any Stored Procedure but with oracle specific SQL. </span></p><br /><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;"></span></p><br /><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">A few days ago, I worked on a little multi-language tool. In a financial application, some labels where needed to be translate from French to English.</span></p><br /><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">Therefore, I decided to make a little tool for the users in order to administrate their label’s translations. </span></p><br /><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">There were three tables:</span></p><br /><br /><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">REF_LABEL:</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">IDT_LABEL PK</span><br /></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">COM_LABEL unique </span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">....</span></p><br /><br /><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;"></span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">REF_LANGUAGE :</span><br /></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">IDT_LNG PK</span><br /></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">COM_LNG</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;"></span></p><br /><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">REF_TRANSLATION:</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">IDT_LABEL FK PK</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">IDT_LNG PK</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">COM_TRANS </span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;"></span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;"></span></p><br /><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">The requirement was to "provide<br />a grid with COM_LABEL, the French translation and the English one for each<br />label. The French and English translation available for modification"</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">First, I defined the main query: </span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;"></span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;color:blue;">string</span><span lang="EN-US" style="font-family:'Courier New';font-size:10;"> strSelect= <span style="color:blue;">" select COM_LABEL, FR.COM_TRANS, EN.COM_TRANS from<br />REF_TRANSLATION EN, REF_TRANSLATION FR, REF_LABEL L"</span><br />+</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;"><span style="color:blue;">" where L.IDT_LABEL = EN.IDT_LABEL "</span> +</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;"><span style="color:blue;">" and L.IDT_LABEL = FR.IDT_LABEL"</span> +</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;"><span style="color:blue;">" and EN.IDT_LNG = 2 -- the English id "</span> +</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;"><span style="color:blue;">" and FR.IDT_LNG = 1 -- the French one "</span> ;<span style="color:blue;">"</span></span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;"></span></p><br /><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">Then, I set the preceding as the CommandText property of an oledbCommand: </span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;"></span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;">System.Data.OleDb.OleDbCommand cmdS = <span style="color:blue;">new</span> System.Data.OleDb.OleDbCommand();</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;">cmdS.CommandText =<br />strSelect ;</span></p><br /><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;">cmdS.Connection = MyValidConnection;</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;"></span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">Next step was the update SQL command,<br />pay attention to the decode function:</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;"></span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;">System.Data.OleDb.OleDbCommand cmdU = <span style="color:blue;">new</span> System.Data.OleDb.OleDbCommand();</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;">cmdU.CommandText = <span style="color:blue;">"update ref_translation set com_trans = decode<br />(idt_lng,1, ?,2,?) where idt_label = ?"</span></span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;">cmdU.Connection =<br />MyValidConnection;</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">"?" are parameters, that I<br />defined by:</span></p><br /><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;"></span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;">cmdU.Parameters.Add(<span style="color:blue;">new</span> System.Data.OleDb.OleDbParameter(<span style="color:blue;">"COM_TRANS_FR"</span>,<br />System.Data.OleDb.OleDbType.Variant, 80, <span style="color:blue;">"LBL_VAL_FR"</span>));</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;">cmdU.Parameters.Add(<span style="color:blue;">new</span> System.Data.OleDb.OleDbParameter(<span style="color:blue;">"COM_TRANS_EN"</span>,<br />System.Data.OleDb.OleDbType.Variant, 80, <span style="color:blue;">"LBL_VAL_EN"</span>));</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;">cmdU.Parameters.Add(<span style="color:blue;">new</span> System.Data.OleDb.OleDbParameter(<span style="color:blue;">"IDT_LABEL"</span>,<br />System.Data.OleDb.OleDbType.Decimal, 0, System.Data.ParameterDirection.Input, <span style="color:blue;">false</span>, ((System.Byte)(4)), ((System.Byte)(0)), <span style="color:blue;">"IDT_LABEL"</span>,<br />System.Data.DataRowVersion.Original, <span style="color:blue;">null</span>));</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;"></span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">The "decode" function is Oracle specific. If you do not know this function, let us says that it is something like a C/C++/C# switch clause or a VB select case, but as a function. It takes<br />at least three arguments and return the third argument if the first is equal to the second, the fifth if the first is equal to the fourth etc... For further<br />info : <a href="http://www.lc.leidenuniv.nl/awcourse/oracle/server.920/a96540/functions33a.htm#1017439">http://www.lc.leidenuniv.nl/awcourse/oracle/server.920/a96540/functions33a.htm#1017439</a></span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;"></span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">Then, I defined my dataAdapter by adding the following:</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;"></span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;">System.Data.OleDb.OleDbDataAdapter daLib = <span style="color:blue;">new </span>System.Data.OleDb.OleDbDataAdapter();</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;">daLib.SelectCommand = cmdS;</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;">daLib.UpdateCommand = cmdU;</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;"></span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:'Courier New';font-size:10;"></span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">Hoops! Two pages, that is too long for one post. </span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;"></span></p><p class="MsoNormal"></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;"></span></p><br /><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">That’s all folks!</span></p><p class="MsoNormal"><span lang="EN-US" style="font-family:Arial;font-size:10;">Comments are welcome!</span></p></div>Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1112367124578788262005-04-01T06:38:00.000-08:002005-04-01T06:52:04.583-08:00oracle functionsToday just a little Oracle trick: the all_arguments view.<br /><br />On your favourite Oracle Client try this :<br /><br /><span style="font-family:courier new;"><strong>select distinct package_name from all_arguments</strong></span><br /><strong><span style="font-family:Courier New;"></span></strong><br /><span style="font-family:Courier New;"><span style="font-family:arial;">this will list every packages including yours on the current schema.</span></span><br /><br />then try this one:<br /><br /><strong><span style="font-family:courier new;"><br />select distinct object_name<br />from all_arguments where package_name like 'STANDARD'</span></strong><br /><strong><span style="font-family:Courier New;"></span></strong><br /><strong><span style="font-family:Courier New;"></span></strong><br /><span style="font-family:arial;">this will list every standard functions installed. I've found it useful when try to remember the exact syntax of "NUMTODSINTERVAL " or "NUMTOYMINTERVAL".</span><br /><span style="font-family:arial;"></span><br /><span style="font-family:Courier New;"></span><br /><span style="font-family:Courier New;">that's all folks </span><br /><span style="font-family:Courier New;"></span><br /><span style="font-family:Courier New;">hope this helps </span><br /><span style="font-family:Courier New;"></span><br /><span style="font-family:Courier New;">comments are welcome</span><br /><strong><span style="font-family:Courier New;"></span></strong><br /><strong><span style="font-family:Courier New;"></span></strong>Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1111761117104337182005-03-25T06:31:00.000-08:002005-03-31T08:29:36.456-08:00linkI just register this blog to this site :<a href="http://www.popdex.com/">www.popdex.com</a>Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1111068112460328072005-03-17T05:38:00.000-08:002007-03-21T06:06:11.676-07:00Quotes & parametersSaw this question on a newsgroup(<a class="gl" href="http://groups-beta.google.com/group/microsoft.public.data.oledb">microsoft.public.data.oledb</a> ) :<br /><br /><em>"How can legally include " ' " (single quote) in my SQL statement?"</em><br /><br />This is a common question and many times it could be a security problem because of SQL injection. Single quote is the SQL string delimiter so you may have to avoid it from you sql code or double it in order to have a valid sql statement.<br /><br />There is a more elegant way to solve this problem: the use of parameters.<br /><br />lets say that cnx is a valid connection the syntax in c# for .net will be :<br /><br /><span style="font-family:courier new;"><strong>OleDbDataAdapter daRes = new OleDbDataAdapter("SELECT IDT_EMP,EMP_NAME FROM EMP where IDT_EMP = ?",cnx);<br />daRes.SelectCommand.Parameters.Add(new System.Data.OleDb.OleDbParameter("IDT_EMP", System.Data.OleDb.OleDbType.VarChar, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(4)), ((System.Byte)(0)), "IDT_EMP", System.Data.DataRowVersion.Current, null));</strong></span><br /><br /><strong><u>notice </u></strong>:If you have many parameters all of them will be represent by a "?". You will have to follow the order of the ?s in the SQLstatement when you add your parameters to the oledbcommand parameters collection .<br /><br />that's all folks<br /><br />hope this helps !<br /><br />comments are welcome.Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1109091602640046092005-02-22T08:58:00.000-08:002005-03-03T03:25:01.103-08:00Oracle sequences and ADO .Net.A few days ago, I twisted my brain on a tricky problem. The point was « the tables in the database have triggers witch inserts a sequence value when inserting a row. The client application uses a dataset and datatables objects with a master-detail relation which requires the primary key to be stored in the datatable objects »<br /><br />That is not a brand new problem. The sequence mechanism is database oriented. That is a good idea. When there are numerous users, it is better to use a centralized id generator. But, an advanced cache oriented data access API like ADO .NET needs to manage this unique identifier without synchronizes the entire dataset.<br /><br />So, last week, I desperately try to build a master/detail dataset model that does not need to know the primary keys of new entries. That was not an elegant solution. Neither it is to use the ADO .net autoId system (as it is client side oriented).<br /><br />I have founded the following solution.<br /><br />Let us have a table named EMP with the following fields:<br /><span style="font-family:courier new;"><strong>ID_EMP Number(6)<br />EMP_NAME VARCHAR2(100)<br /></strong></span><br />..And the following sequence:<br /><br /><span style="font-family:courier new;"><strong>CREATE SEQUENCE PSI_ADMIN.S_EMP<br />START WITH 1<br />INCREMENT BY 1<br />MAXVALUE 999999999999999999999999999<br />MINVALUE 1<br />NOCYCLE<br />CACHE 20<br />NOORDER;<br /></strong></span><br /><br /><br />A typical way to retrieve and manipulate values in .Net is to build dataAdapter object with the insert, delete, update and select Command.<br /><br />For instance:<br /><br /><strong><span style="font-family:courier new;">OleDbDataAdapter da = new OleDbDataAdapter() ;<br />da.SelectCommand.CommandText= "SELECT ID_EMP,EMP_NAME FROM EMP"<br />da.UpdateCommand.CommandText= "UPDATE EMP SET EMP_NAME= ? WHERE ID_EMP= ?" ;<br />da.UpdateCommand.Parameters.Add("EMP_NAME",OleDbType.VarChar,100,"EMP_NAME");<br />da.UpdateCommand.Parameters.Add("ID_EMP" , OleDbType.Numeric,6,"ID_EMP");<br />da.InsertCommand.CommandText= "INSERT INTO EMP(ID_EMP,EMP_NAME) VALUES(?,?)";<br />da.InsertCommand.Parameters.Add("ID_EMP" , OleDbType.Numeric,6,"ID_EMP");<br />da.InsertCommand.Parameters.Add("EMP_NAME",OleDbType.VarChar,100,"EMP_NAME");<br />da.DeleteCommand.CommandText= "DELETE EMP WHERE ID_EMP= ?" ;<br />da.DeleteCommand.Parameters.Add("ID_EMP" , OleDbType.Numeric,6,"ID_EMP");<br /><br />da.SelectCommand.Connection = cnx ;<br />da.UpdateCommand.Connection = cnx ;<br />da.InsertCommand.Connection = cnx ;<br />da.DeleteCommand.Connection = cnx ;</span><br /><br /></strong>….where “cnx” is a valid OLEDB connection to the Oracle database.<br />The "da" object may be use for instance to fill a dataset that can be itself manipulated by a datagrid:<br />…<br /><span style="font-family:courier new;"><strong>da.Fill(ds,"EMP");</strong></span><br />…<br /><br />When synchronizing:<br />…<br /><span style="font-family:courier new;"><strong>da.Update(ds,"EMP");</strong></span><br />…<br />…where "ds" is a valid dataset.<br /><br />This code will works fine as long as you can provide a valid ID_EMP.<br />If you want to use the Oracle sequence, and that is my point, you need something more.<br />You need to handle the “update” event and retrieve the sequence’s next Val from Oracle.<br /><br />Here is how I implement this:<br />First, handle the event in the dataAdapter’s construction:<br />…<br /><span style="font-family:courier new;"><strong>da.RowUpdating +=new OleDbRowUpdatingEventHandler(da_RowUpdating);</strong></span><br />..<br />In addition, somewhere else in the class, put the following method:<br /><span style="font-family:courier new;"><strong>private void da_RowUpdating(object sender, OleDbRowUpdatingEventArgs e)<br />{<br />// Is it an insertion ?<br />if (e.StatementType == StatementType.Insert)<br />da.InsertCommand.Parameters["ID_EMP"].Value= (new OleDbCommand("select S_EMP.nextval from Dual",cnx).ExecuteScalar());<br /><br />}<br /></strong></span><br />When the dataAdapter’s Update method is called, this event fire for each new, deleted or updated row, just before the SQL action is performed.<br />If the action’s type is “insert” the sequence‘s next Val replace the current id_emp parameter.<br /><br />That’s all folks!<br /><br />Hope this helps.<br /><br />Comments are welcome.Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1108035308832371622005-02-10T03:17:00.000-08:002005-02-10T03:36:03.186-08:00Back to work Hello everybody! <br />Waow! I didn't post for about 20 days! Sorry about this. I wasn't able to post because I was <a href="http://travel-cuba.tripod.com/images/antigua/sandals-antigua/beach.jpg ">here</a> and also <a href=" http://www2.canoe.com/archives/voyages/decouvrir/destinations/media/2002/02/20020227-120024-g.jpg">there</a>, I've also been to <a href="http://www.visit-the-virgin-islands.com">this place</a> and <a href="http://www.geographia.com/st-lucia">this one</a>. <br />Oups! I nearly forget this <a href="http://www.top-saint-martin.com/english.htm">island</a> and this <a href="http://www.la-romana.net"> one</a>. <br /> <br />Sorry, that's hard to post code sample today. <br /> <br />Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1106507250317648402005-01-23T09:04:00.000-08:002005-09-09T06:10:13.416-07:00Code generation and self descriptionA few weeks ago I proposed here an example of C# code generation.<br />It remind me an old exercise I used to do when discovering a new language.<br />"The shortest program which produce its own source code on the standard output."<br />Of course, programs which read explicitly their source code to reproduce it are not accepted.<br />The idea of the exercise is to find self reference possibilities offers by the language.<br /><a href="http://mboizeau.free.fr/EXE/echo.exe">I've put the executable here</a> and <a href="http://oraclevsmicrosoft.blogspot.com/2005/06/self-description.html">the source code is here</a>Just download and then launch the echo.exe then click the "itself" button , the complete source code is displayed in the upper richtext box. Then click the "compile" button , the source code is compiled and saved in c:\echo.exe (be careful not to replace a program of your owns).<br />Just launch this new program and compare with the first one.... If you want, you can try to change the code to see effects (debug information shown in the second box).<br /><br />Briefly the principles:<br />I used a double coding representation. The C# code contains in one point a string array declaration with all the lines of the code between "" and coma separated. All the line of the code ? Not exactly, the array declaration is replaced into the array itself by an arbitrary string (I choose a French poet's famous verses). When you click the "it self" button this exact string is replace by a construction of the array declaration. So at this time the array contains all the code including its own declaration. Then a "foreach" instruction join all the lines into one big string which is the exact source code.<br />When you push the "compile" button the text box content is compiled .<br /><br />There is two key factors in this very solution (I'm sure there is at least another solution ).<br />- The declaration syntax of an array in C# which authorize long static arrays.<br />- The compilation feature of the .Net framework.<br /><br />The main part of the code is writed two times. Maybe there is no true connection with this but I can't help comparing this to the double-helix DNA in living cells.<br /><br />The comparison with living cells ends here. This code isn't (AFAIK) a kind of virus or worm and can't be used for malicious purpose. (For instance, runtime compiling features can't be used during an in-line context).<br /><br /><br /><br />Ok, now, two questions :<br /><br />- Is it possible to code that kind of program in PL-SQL? (;-))<br />Maybe next time !<br />- The array based solution is interesting but it doesn't imply the Icodegenerator interface. Is there a solution using a more sophisticated structure than an array?<br />For instance is it possible that a program build its own abstract description usng this interface?<br /><br />That's all folks !<br />Remember there is 10 sorts of people : those who understand native binary code and the others !<br /><br />Comments, answers and suggestions are welcome!Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1106041336911857252005-01-18T01:40:00.000-08:002005-01-18T02:01:26.263-08:00linksA few links today: <br /> <br /><a href='http://www.dotnetspider.com'>C# tutorial and offshore development</a> - dotnetspider offers online training, C# tutorials, offshore development, software outsourcing, link search and sample C# projects with source code. <br /> <br /><a href="http://blog.spsclerics.com ">http://blog.spsclerics.com </a> A Colleague of mine. This blog is mainly about Microsoft Sharepoint portal Server. But you will also find things about C#, .net technology (and the authour's hollidays;-) <br />that's all folks Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1105634751360274282005-01-13T08:42:00.000-08:002005-01-14T08:03:48.223-08:00Oracle data dictionaryHello everybody (Happy coding and merry source code for 2005! ) <br /> <br />Today I would like to talk about Oracle data Dictionary. <br />Without any administration tool it's possible to retrieve information about tables,views and constraints. <br />To understand this article you need an Oracle client connected to a valid schema. <br />(SQL+ for instance) <br /> <br />First I suggest you to try this syntax: <br />select * from DICT <br />This query returns all the views dealing with this schema's dictionary, very useful to retrieve the exact name of a view. The dictionary contains a big amount of views, let's focus on a few one: <br /> <br />Imagine you want to list all the tables you can acces in a schema, you may then try the following: <br /><span style="font-family:courier new;">SELECT * FROM ALL_TABLES</span> <br /><span style="font-family:courier new;"> <br /></span>If you're not a DBA but a developer you may just be interested in your own tables. So try this one: <br /><span style="font-family:courier new;">SELECT * FROM ALL_TABLES <br />WHERE OWNER ='My_name'</span> <br /></span><span style="font-family:courier new;"> <br /></span>The same thing about views: <br /><span style="font-family:courier new;">SELECT * FROM ALL_VIEWS <br />WHERE OWNER ='My_name'</span> <br /></span><span style="font-family:courier new;"> <br /></span>Now imagine you need to know all the constraints of a table : <br /><span style="font-family:courier new;">SELECT * FROM ALL_CONSTRAINTS <br />WHERE <br />table_name= 'My_table' </span> <br /></span> <br />That is useful, but you may want something more fine tunned: <br />What are the foreign keys?: <br /><span style="font-family:courier new;">SELECT * FROM ALL_CONSTRAINTS <br />WHERE CONSTRAINT_TYPE= 'R' <br />and table_name= 'My_table' </span> <br /><span style="font-family:courier new;"> <br /></span>What is the primary key? : <br /><span style="font-family:courier new;">SELECT * FROM ALL_CONSTRAINTS <br />WHERE CONSTRAINT_TYPE= 'P' <br />and table_name= 'My_table'</span> <br /> <br />That's interesting but most of the time you need the name of a field. So, the following retrieves the list of all the fields included in the primary key: <br /><span style="font-family:courier new;">SELECT COLUMN_NAME FROM ALL_CONS_COLUMNS CC, all_constraints C <br />where CC.CONSTRAINT_NAME = C.CONSTRAINT_NAME <br />and C.TABLE_NAME= 'My_Table' <br />and C.CONSTRAINT_TYPE='P'</span> <br /></span><span style="font-family:Courier New;"></span> <br />That's all folks ! <br />Hope this helps, comments are welcome! <br />Marcnoreply@blogger.comtag:blogger.com,1999:blog-8912334.post-1104257738476338282004-12-28T09:56:00.000-08:002004-12-29T01:59:29.480-08:00Code generation with .netHello, today I would like to introduce code generation with c# and .NET. (It may be usefull when dealing with repetitive Database access code). <br /> <br />To start with this feature, here is a complete sample on how to build a ".exe" file, using natives code generation and compilation tools. <br /> <br />The following code will produce, after compilation with csc.exe, a winform application. <br />This application has one purpose: produce another application, a console one. <br />Two framework's objects are important here: <strong>System.CodeDom.Compiler.ICodeGenerator </strong>and <strong>System.CodeDom.Compiler.ICodeCompiler. </strong> <br />The first is a common interface to generate .net code. The second one is used to compile the code. Here I use the cSharp implementation of these interfaces to produce a basic console application. <br /><pre class="csharpcode"><strong><span class="kwrd">using</span> System; <br /><span class="kwrd">using</span> System.Collections; <br /><span class="kwrd">using</span> System.ComponentModel; <br /><span class="kwrd">using</span> System.Windows.Forms; <br /><span class="kwrd">using</span> System.Data; <br /><span class="kwrd">using</span> System.CodeDom; <br /><span class="kwrd">using</span> System