|
Consider the following example for using interface as parameter
class Driver
{
IVehicle vehicleToDrive = null;
Driver(IVehicle vehicleToDrive){
this.vehicleToDrive = vehicleToDrive;
}
public void StartDriving() {
vehicleToDrive.Start();
vehicleToDrive.ChangeGear();
vehicleToDrive.Accelerate();
}
} In the above example, you are programming against an interface. The driver is generic and can drive any vehicle that implements IVehicle . In such situations interfaces are useful.
Following example shows how it is helpful in return types.
IVehicle vehicle = VehicleRepository.Create("Benz");
class VehicleRepository
{
public static IVehicle Create(string vehicleName)
{
IVehicle vehicle = null;
if(vehicleName == "Benz")
vehicle = new Benz();
else if(vehicleName == "Ford")
vehicle = new Ford();
return vehicle;
}
} VehicleRepository.Create method can implement any concrete type of vehicles without changing the return type.
Here is an example when it is used as field.
class BusinessValidation
{
IValidator[] validators = {
new NameValidator(),
new AgeValidator(),
new DesignationValidator() };
void Validate()
{
foreach(IValidator validator in validators){
validator.PerformValidation();
}
}
} Hope it is clear now.
|
|
|
|
|
thanks for the explanation. Now i understand it better.
|
|
|
|
|
shivapriyak wrote: So which method is better?
It depends. If you know the concrete type at the time of writing, use
A a = new A(); If you are using some factory method to create the instance, use
interface1 a = Create() This will help to change the underlying implementation without breaking the contract.
|
|
|
|
|
I have a scenario where we develop a class library which we give to the clients to use in their applications.
Inside the library we have implementations like:
IList<string> ModulesPath = new List<string>(16);
This 'ModulesPath' is used inside the class library (not exposed to the user). So is it correct to have 'ModulesPath' of type IList or List?
However we have another vaiable as:
IIAD i = InstrumentDomain.iad;
here 'IIAD' is a interface(which is in a separate class library) and 'InstrumentDomain' is the class which implements it(this is in a different class library.)
We give both the dlls to the client so that he can write a code as above.
So here, should 'i' be of type IIAD or of type InstrumentDomain i.e. the concrete class?
|
|
|
|
|
shivapriyak wrote: So is it correct to have 'ModulesPath' of type IList or List?
I'd use List ModulesPath = new List(16); here. Because, I know the concrete type is going to be List .
shivapriyak wrote: So here, should 'i' be of type IIAD or of type InstrumentDomain i.e. the concrete class?
This is a good place where writing IIAD i = InstrumentDomain.iad; makes more sense. It also allows you to add a different concrete type in future without making any changes in the contract.
|
|
|
|
|
thanks for the reply. Now i got it.
|
|
|
|
|
Using List also allows you to call its AsReadOnly method if you return it from the method:
public IList<T>
F<T>
(
)
{
List<T> result = new List<T>() ;
...
return ( result.AsReadOnly() ) ;
}
|
|
|
|
|
Dear All,
I want to implement the following functionality:
Read the mapping of the columns of excel and table from XML.
Create a dynamic query to insert the excel data into the columns of the table according to the mapping.
It should not insert in the identity column if any.
Plz help. Its very urgent.
Thanks in advance.
|
|
|
|
|
Member 4959176 wrote: Its very urgent.
This is considered impolite.
Show what you have done to implement this functionality and which parts you find do not work correctly. If you are expecting someone else to do the work for you, you are looking in the wrong place.
|
|
|
|
|
I converted the image to PDF.
I want to extract the PDF as 5 individual image files.
In that case its make a problem. In that PDF File has 5 images, its extracting as one jpg.
IF original PDF contains 5 images means, can extract as 5 individual jpg file
thats the problem for me.
thanks in advance...
|
|
|
|
|
You cannot be doing this without using a third party library. You should post in a forum for that library, or, at least tell us what library it is, and post some code, and hope that someone else here has used it.
Christian Graus
Driven to the arms of OSX by Vista.
Read my blog to find out how I've worked around bugs in Microsoft tools and frameworks.
|
|
|
|
|
Here is the code, im using PDFsharp lib for convert img to PDF.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using PdfSharp;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
namespace TreeListViewDragDrop
{
public partial class ImageToPDF : Form
{
private string srcFile, destFile;
bool success = false;
public ImageToPDF()
{
InitializeComponent();
}
private void btnSelectSrc_Click(object sender, EventArgs e)
{
if (ofdSrcFile.ShowDialog() != DialogResult.OK)
return;
srcFile = ofdSrcFile.FileName;
txbxSrcFile.Text = srcFile;
txbxDestFile.Text =
Path.GetDirectoryName(srcFile) + "\\" +
Path.GetFileNameWithoutExtension(srcFile) + ".pdf";
destFile = txbxDestFile.Text;
}
private void btnSelectDest_Click(object sender, EventArgs e)
{
if (sfdDestFile.ShowDialog() != DialogResult.OK)
return;
destFile = sfdDestFile.FileName;
txbxDestFile.Text = destFile;
}
private void btnConvert_Click(object sender, EventArgs e)
{
errProv.Clear();
if (txbxSrcFile.Text.Length == 0)
{
errProv.SetError(txbxSrcFile, "Please point source file.");
return;
}
else if (txbxDestFile.Text.Length == 0)
{
errProv.SetError(txbxDestFile, "Please point destination file.");
return;
}
success = false;
bw.RunWorkerAsync(new string[2] { srcFile, destFile });
toolStripProgressBar1.Style = ProgressBarStyle.Marquee;
ImageToPDF ImageToPDF = new ImageToPDF();
ImageToPDF.Close();
MainForm PDFForm = new MainForm();
PDFForm.Show();
this.Visible = false;
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
try
{
string source = (e.Argument as string[])[0];
string destinaton = (e.Argument as string[])[1];
PdfDocument doc = new PdfDocument();
doc.Pages.Add(new PdfPage());
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
XImage img = XImage.FromFile(source);
xgr.DrawImage(img, 0, 0);
doc.Save(destinaton);
doc.Close();
success = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
toolStripProgressBar1.Style = ProgressBarStyle.Blocks;
toolStripProgressBar1.Value = 0;
if (success)
MessageBox.Show("The converion ended successfully.", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void button1_Click(object sender, EventArgs e)
{
errProv.Clear();
if (rbSrc.Checked && txbxSrcFile.Text.Length == 0)
{
errProv.SetError(txbxSrcFile, "Please point source file.");
return;
}
else if (rbDest.Checked && txbxDestFile.Text.Length == 0)
{
errProv.SetError(txbxDestFile, "Please point destination file.");
return;
}
try
{
if (rbSrc.Checked)
Process.Start(srcFile);
else if (rbDest.Checked)
Process.Start(destFile);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
|
|
|
|
|
I converted the image to PDF.
I want to extract the PDF as 5 individual image files.
In that case its make a problem. In that PDF File has 5 images, its extracting as one jpg.
IF original PDF contains 5 images means, can extract as 5 individual jpg file
thats the problem for me.
thanks in advance...
|
|
|
|
|
This is a useless question. I explained why above. Posting it twice, only makes it worse.
Christian Graus
Driven to the arms of OSX by Vista.
Read my blog to find out how I've worked around bugs in Microsoft tools and frameworks.
|
|
|
|
|
When i delete the row in a datagridview, it does not act accordingly with my UserDeletingRow event. I am clueless about what is wrong with my codes or why it does not work. Anyone knows the problem? Thanks!
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(15, 70);
this.dataGridView1.MultiSelect = false;
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.ReadOnly = true;
this.dataGridView1.Size = new System.Drawing.Size(92, 173);
this.dataGridView1.TabIndex = 72;
this.dataGridView1.UserDeletingRow += new System.Windows.Forms.DataGridViewRowCancelEventHandler(this.dataGridView1_UserDeletingRow);
private void delete1_Click(object sender, EventArgs e)
{
textBox1.Text = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[dataGridView1.CurrentCell.ColumnIndex].Value.ToString();
dataGridView1.Rows.Remove(dataGridView1.CurrentRow);
}
private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
textBox4.Text = "yeah";
}
|
|
|
|
|
Hi,
i m using the following code for read the attchment but i get the error.
when i send a same id for exp -sender test@test.com to reciever id info@test.com. than i got the error- Could not find a part of the path 'c:\POP3Temp\'.
but i send mail to exp -sender sss@gmail.com to reciever id info@test.com.
than red the attchment fine . no error
try {
Pop3Client email = new Pop3Client("user", "password", "mail.server.com");
email.OpenInbox();
while( email.NextEmail())
{
if(email.IsMultipart)
{
IEnumerator enumerator = email.MultipartEnumerator;
while(enumerator.MoveNext())
{
Pop3Component multipart = (Pop3Component)
enumerator.Current;
if( multipart.IsBody )
{
Console.WriteLine("Multipart body:"+
multipart.Body);
}
else
{
Console.WriteLine("Attachment name="+
multipart.Name); // ... etc
}
}
}
}
email.CloseConnection();
}
pls give the solution.
Thanks
|
|
|
|
|
For several months I've used dynamic compiler in my app that mounted a dll on start-up. But today I came across a painful problem. The code that can be compiled trouble-free in vc#08 has syntax errors according to the 'dynamic' compiler (let me call it dynamic for distinction).
The piece of code in mind looks like this:
void foo()
{
ActorDescription actorDesc = new ActorDescription()
{
BodyDescription = new BodyDescription(70)
};
}
The dynamic compiler shows an error : "error CS1002: ; expected". After simple test I managed to find out that the dynamic compiler probably aims at an older framework and I'm trying to use newer syntax features.
In shortcut, what I was using is this:
System.CodeDom.Compiler.CodeDomProvider cdp =
System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");
System.CodeDom.Compiler.CompilerResults cr = cdp.CompileAssemblyFromFile(parameters, fullPaths);
The functions above are contained by System.dll v2.0 library, so it's not surprising it won't work. Anyway, System.dll v3.5 doesn't exist. Where is the new set of methods to compile according to the newest c# specification? What's the workaround for this? I've been googling for a few hours with no answer.
Thanks in advance!
|
|
|
|
|
CodeDom should use whatever the newest installed compiler is.
I assume that if you installed VS 2010 you'd have the C# v4.0 compiler and it should work fine.
(I haven't, so I can't investigate.)
|
|
|
|
|
Well, I'd say the same until now. But I've got VC# 2008 (Express) for that, so it's rather not the case.
|
|
|
|
|
That's C# 3.0[^]
Execute:
dir /b/s %SystemDrive%\windows\microsoft.net\framework\csc.exe
I get:
C:\>dir /s/b %SystemDrive%\windows\microsoft.net\framework\csc.exe
C:\windows\microsoft.net\framework\v1.1.4322\csc.exe
C:\windows\microsoft.net\framework\v2.0.50727\csc.exe
C:\windows\microsoft.net\framework\v3.5\csc.exe
The version of csc that comes with .net v3.5 implements C# 3.0.
CodeDom should be calling the latest installed version of the compiler.
|
|
|
|
|
Thanks for your answer.
PIEBALDconsult wrote: CodeDom should be calling the latest installed version of the compiler.
It should but did not. Anyway I was given a working solution on another forum.
Dictionary<string, string> options = new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } };
Microsoft.CSharp.CSharpCodeProvider cp = new Microsoft.CSharp.CSharpCodeProvider(options);
Obviously, instead of v3.5 you can specify any other supported version.
|
|
|
|
|
|
i would like to know to capture 'any' click event outside the custom TextBox control.
but not use lostfocus, mousehover, mouseout, etc, etc
i stumbled over this, afterr seeing this in other control from this page.
but they use it different.
kind regards
public partial class exTextBox : TextBox
{
protected exTextBox parent;
public exTextBox Parent
{
get { return parent; }
}
public exTextBox()
{
InitializeComponent();
TextBoxParent(this.parent);
}
public void TextBoxParent(exTextBox parent)
{
parent.Click += new EventHandler(parent_Click);
}
void parent_Click(object sender, EventArgs e)
{
MessageBox.Show("click", "click", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
--------------------------------------------------------------
errro: Object reference not set to an instance of an object.
public exTextBox()
{
this.Parent.Click +=new EventHandler(parent_Click);
}
void parent_Click(object sender, EventArgs e)
{
MessageBox.Show("click", "click", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Bad = knowing 2 much
modified on Wednesday, September 23, 2009 3:46 PM
|
|
|
|
|
The Parent property isn't set until the handle for the control is created AFAIK.
Try creating the event handler in an overrided OnHandleCreated method. This works for me.
using System;
using System.Windows.Forms;
namespace TestApp
{
public partial class Form1 : Form
{
ExtendedTextBox extendedTextBox1;
public Form1()
{
InitializeComponent();
extendedTextBox1 = new ExtendedTextBox();
Controls.Add(extendedTextBox1);
}
}
public class ExtendedTextBox : TextBox
{
public ExtendedTextBox()
{
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
Parent.Click += new EventHandler(Parent_Click);
}
void Parent_Click(object sender, EventArgs e)
{
MessageBox.Show(
"click",
"click",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
}
|
|
|
|
|
hey, thanx
indeed, i copy this to a new project, it works fine.
but when i copy the following lines to my old project,it's doesn't.
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
Parent.Click += new EventHandler(Parent_Click);
}
void Parent_Click(object sender, EventArgs e)
{
MessageBox.Show(
"click",
"click",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
the extended Textbox class gets compiled to dll.
Bad = knowing 2 much
|
|
|
|