In principal, despre .NET, VB6. C#,VB.NET, ASP.NET Apoi despre programare si multe alte chestii ... de programare.

Subscribe RSS   Mini tools List

joi, decembrie 21, 2006

Top .NET tools
Va rog sa folositi acest URL NOU de la
http://serviciipeweb.ro/iafblog/

Ma intrebam de ce nu imi place Ed Tittel - pare a fi prost informat, si cind e cit de cit bine informat, pare ca face reclama platita. Acum m-am convins ca e adevarat.
Iata diferentele, in privinta recomandarilor Top .NET tools:
Ed Tittel
Mike Gunderloy ( de citit neaparat)- as adauga la lista de free WinMerge

Oh , si daca nu ati citit, Ten Must-Have Tools Every Developer Should Download Now

Post page: http://serviciipeweb.ro/iafblog/2006/12/21/Top+NET+Tools.aspx

Weblog post by 'admin' on 'Top .NET tools'

Categories:discutii;programare

sâmbătă, decembrie 16, 2006

regional settings, Excel ,CSV si OleDbConnection
Va rog sa folositi acest URL NOU de la
http://serviciipeweb.ro/iafblog/

Nebunul de excel, cind salveaza sub csv, tine seama de regional settings.Iar la mine List separator este ; (ca in Romana) - nu virgula( deci csv nu mai e comma separated values)

Asa se face ca la mine pe masina cind vreau sa citesc cu driver-ul de OleDbConnection(Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strDir + ";Extended Properties='Text;HDR=NO;FMT=Delimited'") vrea neaparat virgula - si habar nu are ca sunt mai multe coloane...si intra in nebunie...
Dar cum s-ar rezolva nu stiu

Post page: http://serviciipeweb.ro/iafblog/2006/12/15/regional+Settings+Excel+CSV+Si+OleDbConnection.aspx

Weblog post by 'admin' on 'regional settings, Excel ,CSV si OleDbConnection'

Categories:.NET;programare

luni, decembrie 11, 2006

editarea de obiecte
Va rog sa folositi acest URL NOU de la
http://serviciipeweb.ro/iafblog/

Va trebui, asa cum am promis, sa facem adaugarea/ modificarea / stergerea de obiecte( pe scurt, C(R)UD – create, (read), update, delete). Luam un buton din Toolbox, il tragem pe forma, ii setam din proprietati ( apasati F4) numele la btnAdd si text la “&Add” ( &A e pentru ca, atunci cind apasam <ALT> + A , sa fie ca si cind dam click pe button)

 

 

Acum dati dublu click pe button – si veti intra in codul de click. Avem o problema : trebuie ca user-ul sa introduca numele Publisher-ului. O sa creeam o noua forma : Click dreapta pe BookWin, Add => Windows Form- si ii veti da denumirea de frmPublisherAdd.cs. Apasati F4 si la Text puneti : Add Publisher

 

Adaugati un Label( Name: lblName , Text : &Name) si un textbox ( Name : txtName)

Adaugam acum un Button de Add ( Name : btnAdd, Text : &Add) si unul de Exit (Name : btnExit, Text : E&xit)

 

Codul de pe btnExit e cel mai usor ( dati dublu click pe buton)

  private void btnExit_Click(object sender, EventArgs e)

        {

            this.Close();//close the form

        }

Codul de pe Button-ul de Add :

 

            private void btnAdd_Click(object sender, EventArgs e)

        {

            BookObjects.Publisher p = new BookObjects.Publisher();

            p.Name = txtName.Text;

            p.Save();

this.Close();//close the form

        }

 

E clar ca trebuie sa scriem metoda de Save pe Publisher

Inapoi la clase : si acolo vom scrie metoda de save.

  public void Save()

        {

            string strSQL = " insert into Publisher(NamePublisher";

            if (!string.IsNullOrEmpty(this.Site))

                strSQL += ",SitePublisher ";

 

            strSQL += " ) Values (";

 

            strSQL += "'" + this.Name.Replace("'","''") + "'";//terminator for string in SQL is ' - so replace with ''

           

            if (!string.IsNullOrEmpty(this.Site))

                strSQL += "," +"'"+ this.Site.Replace("'", "''") +"'";//terminator for string in SQL is ' - so replace with ''

 

 

            strSQL += " )";

 

           

            Settings.ExecuteSQL(strSQL);

           

           

           

        }

 

In sfirsit, sa scriem codul pentru adaugare de pe forma de list:

E clar ca va trebui sa facem re incarcarea datelor  - deci o sa luam codul de pe frmPublisherList_Load si o sa il punem in o functie generica , RebindData()

 

private void btnAdd_Click(object sender, EventArgs e)

        {

            frmPublisherAdd f = new frmPublisherAdd();

            f.ShowDialog(this);

            RebindData();

        }

 

private void RebindData()

        {

BookObjects.ColPublisher publishers = new BookObjects.ColPublisher();

            publishers.Load();

            colPublisherBindingSource.DataSource = publishers;

        }

 

Sa verificam functionarea

Dati CTRL+ F5 , apasati Add – introduceti un nume – apasati Add – si verificati ca se vede in lista ceea ce ati introdus.

 

Sa facem acum stergerea.

Adaugati alt buton(Name = btnDelete, Text = &Delete) si sa scriem cod pentru delete

private void btnDelete_Click(object sender, EventArgs e)

        {

 

            BookObjects.Publisher p = colPublisherBindingSource.Current as BookObjects.Publisher;

            if (p != null)

            {

                //avert the user

                if (MessageBox.Show(this, "Delete " + p.Name, "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)

                    return;

 

 

                p.Delete();

                RebindData();

            }

        }

 

In sfirsit, sa scriem codul pentru update: iarasi buton, iarasi cod

private void btnUpdate_Click(object sender, EventArgs e)

        {

            BookObjects.Publisher p = colPublisherBindingSource.Current as BookObjects.Publisher;

 

            if (p == null)

                return;

 

            frmPublisherUpdate f = new frmPublisherUpdate(p);

            f.ShowDialog(this);

            RebindData();

        }

 

Pentru asta, adaugam o alta forma, in care sa facem update .

Dar avem neaparata nevoie de un publisher pe care sa facem update.Vom modifica constructorul formei ca sa accepte ca parametru de intrare un publisher.

 

Ca sa punem valorile deja obtinute in text box-uri, avem 2 variante :

Fie codam de mina de doua ori ( ceva de genul  txtName.Text= m_Publisher.Name si , pe salvare, m_Publisher.Name= txtName.Text),fie lucram cu DataBindings direct . Prefer acum, pentru rapiditate, a doua varianta :

 

public partial class frmPublisherUpdate : Form

    {

        private BookObjects.Publisher m_Publisher;

        public frmPublisherUpdate(BookObjects.Publisher pub)

        {

            m_Publisher = pub;

            InitializeComponent();           

        }

 

       

        private void frmPublisherUpdate_Load(object sender, EventArgs e)

        {

            txtName.DataBindings.Add("Text", m_Publisher, "Name");

            txtSite.DataBindings.Add("Text", m_Publisher, "Site");

        }

 

        private void btnSave_Click(object sender, EventArgs e)

        {

            m_Publisher.Update();

            this.Close();

        }

 

        private void btnExit_Click(object sender, EventArgs e)

        {

            this.Close();

        }

 

 

    }

 

Sa scriem si codul de salvare pe publisher :

  public void Update()

        {

            string strSQL = " update Publisher set ";

            strSQL += " NamePublisher = ";

 

            strSQL += "'" + this.Name.Replace("'", "''") + "'";

 

            strSQL += ",";

 

            strSQL += " SitePublisher = ";

 

            strSQL += "'" + this.Site.Replace("'", "''") + "'";

 

 

            strSQL += " where IDPublisher = " + this.IDPublisher;                           

            strSQL += " ";

 

 

            Settings.ExecuteSQL(strSQL);

        }

 

 

Ca tema de acasa, ramine sa faceti acelasi lucru pentru tabela Author.

Data viitoare o sa facem un mic refactoring de code... si o sa facem un program de setup pentru aplicatia Windows.

 

           

Post page: http://serviciipeweb.ro/iafblog/2006/12/11/editarea+De+Obiecte.aspx

Weblog post by 'admin' on 'editarea de obiecte'

Categories:programare;tutoriale

vineri, decembrie 08, 2006

Excel si C#
Va rog sa folositi acest URL NOU de la
http://serviciipeweb.ro/iafblog/

Dupa ce m-am batut cu referintele COM ( care mor imediat daca e proiect consola, dar care mai traiesc daca e ASP.NET) am reusit sa implementez IDisposable peste (aproape) fiecare obiect de la Excel.
Astfel incit am un Range_Disposable care inglobeaza / deriveaza din Range, un WorkSheet_Disposable care inglobeaza/deriveaza din Worksheet ( si la care metoda get_Range intoarce Range_Disposable).

Observatie 1.
    In proiectul consola, daca inchid Excel ( app.Quit(); Marshal.ReleaseComObject()) si am citeva Range_Disposable la care nu am aplicat Dispose, atunci app.Quit le apeleaza si pe ele.
    In proiectul ASP.NET , daca fac acelasi lucru, app.Quit da Access Denied...

Observatia 2.
    Totul se poate repara usor , folosind binecunoscutul using(Range_Disposable r = W.get_range())



Post page: http://serviciipeweb.ro/iafblog/2006/12/07/Excel+Si+C.aspx

Weblog post by 'admin' on 'Excel si C#'

Categories:programare;Excel;.NET

duminică, decembrie 03, 2006

Part 4 : .NET programming
Va rog sa folositi acest URL NOU de la
http://serviciipeweb.ro/iafblog/

If you have not read yet the first parts, please found them here: Part 1 , Part 2 and Part 3

 

 

Now we have the Access database on the C:\Book\BookData – and the dll to load data is on the C:\Book\BookObjects.

We will create a Windows Forms project to see the data that is in the MDB file.

Right click on the solution -and choose: Add => New Project => and choose Windows Application. Put the name BookWin. A new form is created for you by default.

Change the name from Form1 to frmPublisherList.cs, double click on the file, press F4 to bring Properties window up front and change the Text from Form1 to List of Publishers.

Now we must tell to the windows project to use the objects project that we created earlier. Right click BookWin project in the Solution Explorer, click „Add reference” and go to the Projects tab on the next window. Double Click the BookObjects project.Compile(CTRL+SHIFT+B).

 

I must found a way to copy the MDB in the same location as the executable, in order that the path can function easily even the application will be deployed in other paths. (Not every user will easily agree to deploy the application on the same path as we do, C:\Book – maybe he wants to install in other places).

The solution to be always in sync is to perform the copy automatically and precisely when the build is complete.

Right click on BookWin project from Solution Explorer, select properties (or find in menu Project => Book Project Properties)

On the “build events“tab you have a pre and a post build event command line

We will wrote this code in the post build

copy $(ProjectDir)..\BookData\*.mdb $(TargetDir)

That means copy all MDB files from the following dir C:\Book\BookData (obtained as following from the project dir (C:\Book\BookObjects\), the up (C:\Book\), the to BookData (C:\Book\BookData)) to TargetDir (does no matter if debug or release)

Save and compile (CTRL + SHIFT + B)

Now in the C:\Book\BookObjects\bin\Release or in the C:\Book\BookObjects\bin\Debug must be another copy of the MDB file.

Very good * let’s write now the connection to the MDB. Right Click on BookWin in the Solution Explorer – click Add => New Item => and choose “Application Configuration File” ( default name :App.config – do not change this!) and put the following lines:

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<add key="DatabaseUsed" value="MDB"/>

<!-- possible values : MDB, SQLServer-->

</appSettings>

<connectionStrings>

<add name="MDB" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\book.mdb;User Id=admin;Password=;"/>

<!-- TODO : add for asp.net application the connection string with SQL Server-->

</connectionStrings>

</configuration>

Now it’s the moment to load the records. We put code in the settings.cs file to be able to switch connection at run-time:

public static DbConnection TheConnection

{

get

{

switch (TheDatabase)

{

case DatabaseUsed.MDB:

OleDbConnection oc = new OleDbConnection(ConnectionStringMDB);

return oc;

case DatabaseUsed.SQLServer:

SqlConnection sc=new SqlConnection(ConnectionStringSQLServer);

return sc;

default:

// Maybe throw an error that config file has not been initialized with

// the database type ?

return null;

}

}

}

 

And to load Records:

public static IDataReader Load(string CommandLine, DbConnection dbcon)

{

 

if (!(dbcon.State == ConnectionState.Open))

dbcon.Open();

 

DbCommand dc = null;

switch (TheDatabase)

{

case DatabaseUsed.MDB:

dc = new OleDbCommand(CommandLine);

break;

case DatabaseUsed.SQLServer:

dc = new SqlCommand(CommandLine);

break;

default:

//TODO : throw specific error that database type does not properly have been initialized

break;

}

dc.CommandType = CommandType.Text;

dc.Connection = dbcon;

return dc.ExecuteReader();

 

return null;

 

 

}

 

 

As you see, we return a DbConnection no matter we use the OleDbConnection or SqlConnection .

Now let’s fill in the Load code in the ColPublisher file:

using System;

using System.Collections.Generic;

using System.Text;

using System.Data;

using System.Data.Common;

 

namespace BookObjects

{

public class ColPublisher : System.Collections.ObjectModel.KeyedCollection<string,Publisher>

{

protected override string GetKeyForItem(Publisher item)

{

return "K" + item.IDPublisher;

}

public void Load()

{

DbConnection db = Settings.TheConnection;

using (db)

{

db.Open();

IDataReader ir = Settings.Load("select IDPublisher, NamePublisher, SitePublisher from Publisher", db);

while (ir.Read())

{

Publisher p = new Publisher();

p.FillObject(ir);

//TODO : add p into the collection

}

}

}

 

}

}

 

We realize now that the ColPublisher is not a collection where to add the new publisher p. Fortunately, the .NET collection is enough big to contain many collection.

Just look into the System.Collections namespace, then into System.Collections.ObjectModel and into System.Collections.Specialized. You will find many more on the net ( for example, an implementation of a Set collection : http://www.codeproject.com/csharp/sets.asp)

We will derive the ColPublisher from the System.Collections.ObjectModel.KeyedCollection<string,Publisher> .We must wrote how to generate the key for a specific Publisher -and what Key is better than the ID ?

protected override string GetKeyForItem(Publisher item)

{

return "K" + item.IDPublisher;

}

 

Now we can wrote the Load method properly :

using System;

using System.Collections.Generic;

using System.Text;

using System.Data;

using System.Data.Common;

 

namespace BookObjects

{

public class ColPublisher : System.Collections.ObjectModel.KeyedCollection<string,Publisher>

{

protected override string GetKeyForItem(Publisher item)

{

return "K" + item.IDPublisher;

}

public void Load()

{

DbConnection db = Settings.TheConnection;

using (db)

{

db.Open();

IDataReader ir = Settings.Load("select IDPublisher, NamePublisher, SitePublisher from Publisher", db);

while (ir.Read())

{

Publisher p = new Publisher();

p.FillObject(ir);

this.Add(p);

}

}

}

 

}

}

 

And use it from the Form :

Double click on the frmPublisherList.cs and drag a DataGridView to the form

 

Now configure the data source:

 

Click on “(none)” and select “add new data source”

In the next dialog, choose “Object”



 

and press next.

Now expand the BookObjects node and choose “ColPublisher”. Press Next and then Finish.

To the form is a new control added: colPublisherBindingSource – and the Grid has already the columns defined.

Now wrote the data to load the data from the database:

Double click on form, and you will find yourself in the Form_Load event :

private void frmPublisherList_Load(object sender, EventArgs e)

{

BookObjects.ColPublisher publishers = new BookObjects.ColPublisher();

publishers.Load();

colPublisherBindingSource.DataSource = publishers;

}

 

Now the results – right click on BookWin – and select “Set as startup project”

Now press F5 * and wait to see the results. If the best case, you will see a form with no data at all – and this is very correct – because of the fact that are no items in the Book.mdb

 

In the next lesson we will wrote code to do insert of a new Publisher and viewing him on the form ( finally!)

 

Recommended readings:

CSLA : http://www.lhotka.net/cslanet/ – a good framework to handle all the security, scalability , binding and other issues ( and, most of all, free).

 

 



 

 

 

 

Post page: http://serviciipeweb.ro/iafblog/2006/12/04/Part+4+NET+Programming.aspx

Weblog post by 'admin' on 'Part 4 : .NET programming'

Categories:programare;tutoriale

 
Acest blog s-a mutat la http://www.serviciipeweb.ro/iafblog/