|
In the below code snippet, Ring() method defined in Classes "SmartPhone", "BasicPhone" etc is returning a custom datatype called "Sound". As far as I have read few topics, custom datatypes can be implemented using Classes, Structures etc.Normally, I have worked with methods returning in-built datatypes like int,string etc but have no idea about methods returning custom datatypes like "Sound" as per mentioned example. So, how should I write/define the Class "Sound" for the above program to work
OR (an other explanation w.r.t the question asked)
If code execution calls "Phone.Ring()" statement in the foreach loop defined Main() method , let's say a message "MP3 music is playing" for Smartphone, "Polyphonic music is playing" for SemiSmartPhone, "8BitMusic is playing" for BasicPhone to be displayed on the console screen.
Let me know if you need more details.To be honest, had posted in other forums, but couldn't get an answer yet.As far as I remember, this code example has been picked from codeproject.com I believe. Thanks
My Program on hold:
class Sound
{
???
}
interface IRingable
{
public Sound Ring();
}
class SmartPhone : IRingable
{
public Sound Ring()
{
return PlayMp3Music();
}
}
class SemiSmartPhone : IRingable
{
public Sound Ring()
{
return PolyPhonicMusic();
}
}
class BasicPhone : IRingable
{
public Sound Ring()
{
return 8BitMusic();
}
}
class Main
{
public static void Main(string[] args)
{
List<IRingable> phones = new List<IRingable>();
IRingable htc = new SmartPhone();
phones.Add(htc);
IRingable samsung = new SemiSmartPhone();
phones.Add(samsung);
IRingable nokia = new BasicPhone();
phones.Add(nokia);
foreach (IRingable phone in phones)
{
phone.Ring();
}
}
}
|
|
|
|
|
Some of your code is okay but you seem to be running into a little bit of a misunderstanding about what Sound would be doing. Basically, your Sound idea would suggest that you would have only one Sound class and somehow it would be able to satisfy the different sounds, be they polyphonic, etc. The reality is, you would need multiple Sound classes, and you would use an appropriate one of these.
So, the question you have here is, how would you declare these classes and how would you use them? To answer this, you are first going to have to decide whether Sound contains any functionality at all, or whether it is merely a contract. If it's merely a contract, then you would get rid of the Sound class altogether, and just have an interface that the different sound classes would play. Let's assume, though, that the Sound class has some functionality that is common across the different implementations - it could be that the Sound class is responsible for loading a sound in and then playing it, and the only difference in your implementations is which sound it brings in. In this case, you would make your Sound class abstract and you would inherit from this. This might give you something like this:
public abstract class Sound
{
public void PlaySound()
{
SoundPlayer soundPlayer = new SoundPlayer(SoundName);
soundPlayer.Play();
}
protected abstract string SoundName { get; }
} Now, in this code, we can see that the SoundName property is marked as abstract which means that derived classes must provide an implementation. So, let's create an appropriate derived class here
public class PolyphonicSound()
{
protected virtual string SoundName { get { return "MySoundFile.wav"; } }
} Now, with this in place, any time you want to use a polyphonic sound, you would use an instance of this class. As an example, you would change SemiSmartPhone to return the PolyphonicSound class like this:
class SemiSmartPhone : IRingable
{
public Sound Ring()
{
return new PolyphonicSound();
}
} Now, the final bit that needs to be sorted out (other than adding the other appropriate sound classes), is to sort out your foreach. Your current implementation has a return value that it does nothing with. We know that Ring will return the appropriate Sound implementation and that they have a PlaySound method that we need to call, so change this instead to be:
foreach (IRingable phone in phones)
{
Sound sound = phone.Ring();
sound.PlaySound();
}
This space for rent
|
|
|
|
|
Thank you Pete O'Hanlon. I was able to understand your explanation & was quite useful. The question which I posted was from an article of code project. The link for the same is Why do we need Interfaces?[^]
The said example is under the section "Interfaces Treat different types in the Same Way". I was unable to run that example as "Sound" in the code is behaving like a custom datatype (correct me if I am wrong) and the Ring() in all classes was returning "Sound". There was no implementation for "Sound" class or structure in that program. So, just wanted to know from experts as how would a "Sound" class be defined for that program to run successfully. Any ways, thanks a lot & appreciate for taking time in replying.
|
|
|
|
|
Member 12984275 wrote: What should the implementation of this class be for the program It should be whatever is necessary to do whatever you want it to do. If you do not understand how to create a C# class then take a look at Classes and Structs (C# Programming Guide)[^].
|
|
|
|
|
i saw couple of sample code searching google and people said we can run ppt slide show inside webbrowser controls. so i did the same.
here is my code
webBrowser1.Dock = DockStyle.Fill;
webBrowser1.Navigate("about.blank");
webBrowser1.Navigate(@"e:\Presentations-Tips.ppt");
when i run the code then a dialog come which ask me to choose one option out of 3 and i select open option. after selection open option power point apps open but no slide show run in my webbrowser control.
here is the screen shot url [screenshot]
i want to run ppt slide show inside my browser controls and i want also no dialog should come with 3 options and also ppt app should not run.
so guide me how could i run ppt slide show in my browser control without opening power point application. thanks
tbhattacharjee
|
|
|
|
|
|
please guide me what argument i need to pass with ppt files name when run with Process.Start as a result ppt slide should start automatically
System.Diagnostics.Process.Start("pptfilename.pptx")
thanks
tbhattacharjee
|
|
|
|
|
Did you even TRY to Google for "PowerPoint command line arguments" before you posted this?
It's called "reading the documentation".
|
|
|
|
|
|
So did you keep reading all the way down the article, like to where it mentions the /N# switch? Apparently not.
Research is a skill you MUST have to survive doing this job.
|
|
|
|
|
He's a help vampire
This space for rent
|
|
|
|
|
yes i googled it but face some problem. i use the below code
webBrowser1.Dock = DockStyle.Fill;
webBrowser1.Navigate("about.blank");
webBrowser1.Navigate(@"e:\Presentations-Tips.ppt");
when i run the code then a dialog come which ask me to choose one option out of 3 and i select open option. after selection open option power point apps open but no slide show run in my webbrowser control.
[here is the screen shot url]
the problem is when i run the above code then first power point application is open which i do not want. also nothing start showing in web browser controls.
basically i want to run ppt slide show in web browser controls but power point application will not run. now tell me how it will be possible and what code i need to use. thanks
tbhattacharjee
|
|
|
|
|
That's not your original code.
You don't have the control over which slide is shown using the webbrowser control method.
|
|
|
|
|
I have a basic WindowsForm C# application that loops thru a key (Dependencies) and list all values of all subkeys found. It is compiled to use Any CPU (unselecting "Prefer 32-bit" option as well )
registry hive looks like this:
Dependencies
-{{050d4fc8-5d48-4b8f-8972-47c82c46020f}
.....
.....
-{030d4fc8-5d48-4b8f-8342-47c82c46020f}
...
...
-Microsoft.VS.VC_RuntimeAdditionalVSU_x86,v11
-Microsoft.VS.VC_RuntimeMinimumVSU_amd64,v12
....
....
When I run the application in server 2012 or higher, the application reads all values found in each subkey (works great) but when I ran it in Windows 10 Pro, only the subkeys that start with Microsoft.VS.VC_..etc are read.
Any ideas how to fix it?
|
|
|
|
|
picasso2 wrote: Any ideas how to fix it? Without seeing some code it is impossible. You need to use regedit to look at the entries and see if there are any differences between the two systems. Then use your debugger to track the code and see exactly where the problem occurs. See also 32-bit and 64-bit Application Data in the Registry (Windows)[^].
|
|
|
|
|
I am using a third party reference, which is a COM object. The COM object has an Open and Close function and I need to make sure that Close is always called whenever possible. I wrote a wrapper class that implements IDisposable and in the Dispose function, I try to call the Close function. However I get a System.Runtime.InteropServices.InvalidComObjectException when I try to call the close function with additional details of "COM object that has been separated from its underlying RCW cannot be used."
public class MyWrapper : IDisposable
{
private Session _mySession = new Session();
public void Open() { _MySession.Open(); }
public void Close() { _MySession.Close(); }
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose(bool disposing) {
_MySession.Close();
}
~MyWrapper() { Dispose(false); }
}
From my (limited) understanding, there are two reasons why I am getting the exception.
1) The Finalizer is running and calling the destructor, but because the finalizer is on a separate thread I get the error.
2) Based on this Stack Overflow[^] post, the Runtime Callable Wrapper (RCW) has it's own finalizer which is being called before mine, and getting rid of the COM object.
I don't know if either of these, or both of these are true, but what is the recommended way to implement a COM object that needs to have finalizer code run?
|
|
|
|
|
Hello, I have a Problem. I'd like to list all existing files on a Network share. My Problem: When I save my Username and Password in Windows I can access the NAS with Visual Studio and list the files.
Here is my code:
string path = @"\\192.168.0.5\Share";
string userName = @"User";
string userPassword = "Password";
string userHost = "192.168.0.5";
NetworkCredential theNetworkCredential = new NetworkCredential(userName, userPassword);
CredentialCache theNetCache = new CredentialCache();
theNetCache.Add(new Uri(path), "Basic", theNetworkCredential);
var g = theNetworkCredential.GetCredential(new Uri(path), "Basic");
var tt = CredentialCache.DefaultNetworkCredentials;
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(path);
IReadOnlyList<StorageFile> fileList = await folder.GetFilesAsync();
foreach (StorageFile sF in fileList)
{
}
|
|
|
|
|
|
If I login at the NAS in Windows to access the files with Internet Explorer, the Credentials are saved in Windows and it works. When I don't login in Windows at the NAS before, or i delete the Credentials in the control Panel, it says access denied.
I'd like to save the Credentials in C# into the saved Login Passwords (logon-information, in German it is called Windows-Anmeldeinformationen, but not the Web-logon-Information)
|
|
|
|
|
Please rate it 1-10 where 10 is the highest. I only learned VB.NET from school and only have self-taught C# so most of the logic here I got from open-source projects and some throught. Took me hours to refine this but I still feel I can do better (I know how to use constructors, accessors, and such but I didn't use them here).
It is a simple INSERT/UPDATE/DELETE form with datagridview/listbox display.
MainForm:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Workers {
public partial class ManageUserRecords : Form {
string getID { get; set; }
string Emp_ID, Username, Password, Type, FirstName, MInitial, LastName, FullName, Address, Phone, Email;
public ManageUserRecords() {
InitializeComponent();
}
private void ManageUserRecords_Load(object sender, EventArgs e) {
load_Dgv();
hide_GridColumns();
load_lb();
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
set_TxtBox();
}
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
set_TxtBox();
}
private void dataGridView1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down) {
set_TxtBox();
}
}
private void btnInsert_Click(object sender, EventArgs e) {
if ((string)btnInsert.Tag == "Add New") {
btnInsert.Tag = "Save Add";
btnInsert.Text = "Save";
clear_All();
txtFName.Select();
} else if ((string)btnInsert.Tag == "Save Add") {
if (txtFName.TextLength < 1 || txtLName.TextLength < 1) {
MessageBox.Show("First Name & Last Name is required");
return;
} else if (txtUsername.TextLength < 1 || txtPassword.TextLength < 1) {
MessageBox.Show("Username & Password is required");
return;
} else if (cbType.Text == "") {
MessageBox.Show("Account Type is required");
return;
}
btnInsert.Tag = "Add New";
btnInsert.Text = "Add New";
Username = txtUsername.Text;
Password = txtPassword.Text;
Type = cbType.Text;
FirstName = txtFName.Text;
MInitial = txtMInitial.Text;
LastName = txtLName.Text;
FullName = FirstName + " " + MInitial + " " + LastName;
Address = txtAddress.Text;
Phone = txtPhone.Text;
Email = txtEmail.Text;
new FormWorkers().insert_Record(FullName, Username, Password, Type, FirstName, MInitial, LastName, Address, Phone, Email);
string userInfo = String.Format("Details:{0} Name : {1}{0} Address : {2}{0} Phone : {3}{0} Email : {4}{0}{0}Account:{0} Username : {5}{0} Type : {6}", Environment.NewLine, FullName, Address, Phone, Email, Username, Type);
MessageBox.Show(String.Format("Record Added!{0}{0}" + userInfo, Environment.NewLine));
load_Dgv();
load_lb();
clear_All();
}
}
private void btnUpdate_Click(object sender, EventArgs e) {
int count = dgvEmployees.SelectedRows.Count;
if (count == 1) {
if ((string)btnUpdate.Tag == "Update New") {
btnUpdate.Tag = "Save";
btnUpdate.Text = "Save";
accessControls();
} else if ((string)btnUpdate.Tag == "Save") {
btnUpdate.Tag = "Update New";
btnUpdate.Text = "Update";
Emp_ID = getID;
Password = txtPassword.Text;
Type = cbType.Text;
FirstName = txtFName.Text;
MInitial = txtMInitial.Text;
LastName = txtLName.Text;
FullName = FirstName + " " + MInitial + " " + LastName;
Address = txtAddress.Text;
Phone = txtPhone.Text;
Email = txtEmail.Text;
new FormWorkers().update_Info(Emp_ID, FullName, Password, Type, FirstName, MInitial, LastName, Address, Phone, Email);
MessageBox.Show("Record updated");
load_Dgv();
load_lb();
clear_All();
}
} else {
MessageBox.Show("Select an item from the list to update.");
}
}
private void btnDelete_Click(object sender, EventArgs e) {
int count = dgvEmployees.SelectedRows.Count;
if (count == 1) {
Emp_ID = getID;
new FormWorkers().delete_Record(Emp_ID);
MessageBox.Show("Record deleted");
load_Dgv();
load_lb();
clear_All();
} else {
MessageBox.Show("Select an item from the list to delete.");
}
}
void accessControls() {
foreach (Control txt in this.Controls) {
if (txt is TextBox) {
txt.Enabled = true;
}
}
foreach (Control txt in groupBox1.Controls) {
if (txt is TextBox) {
txt.Enabled = true;
}
cbType.Enabled = true;
}
}
void load_Dgv() {
new FormWorkers().load_Db();
dgvEmployees.DataSource = FormWorkers.sqldt;
}
void load_lb() {
listBox1.Items.Clear();
new FormWorkers().load_List();
foreach (DataRow dtrows in FormWorkers.lbdt.Rows) {
FormWorkers.dtrow = dtrows;
listBox1.Items.Add("(" + FormWorkers.dtrow["Emp_ID"] + ") " +
"Name: " + FormWorkers.dtrow["Name"]);
}
}
void set_TxtBox() {
DataGridViewRow CurrentRow = dgvEmployees.CurrentRow;
getID = CurrentRow.Cells[0].Value.ToString();
txtFName.Text = CurrentRow.Cells[5].Value.ToString();
txtMInitial.Text = CurrentRow.Cells[6].Value.ToString();
txtLName.Text = CurrentRow.Cells[7].Value.ToString();
txtAddress.Text = CurrentRow.Cells[2].Value.ToString();
txtPhone.Text = CurrentRow.Cells[3].Value.ToString();
txtEmail.Text = CurrentRow.Cells[4].Value.ToString();
txtUsername.Text = CurrentRow.Cells[8].Value.ToString();
cbType.Text = CurrentRow.Cells[9].Value.ToString();
}
void hide_GridColumns() {
int colcount = dgvEmployees.Columns.Count - 1;
for (int i = 5; i <= colcount; i++) {
dgvEmployees.Columns[i].Visible = false;
}
}
void clear_All() {
foreach (Control txt in this.Controls) {
if (txt is TextBox || (string)btnDelete.Tag != "Delete") {
txt.Text = "";
if (txt.Enabled == true) {
txt.Enabled = false;
} else {
txt.Enabled = true;
}
}
}
foreach (Control txt in groupBox1.Controls) {
if (txt is TextBox || (string)btnDelete.Tag != "Delete") {
txt.Text = "";
if (txt.Enabled == true) {
txt.Enabled = false;
cbType.Enabled = false;
} else {
txt.Enabled = true;
cbType.Enabled = true;
}
}
cbType.SelectedIndex = 0;
}
dgvEmployees.ClearSelection();
}
}
}
MainForm Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace Workers {
class FormWorkers {
SqlCommand cmdSelect, sqlInsert, sqlUpdate, sqlDelete;
SqlDataAdapter sqlSelect;
SqlDataReader rdr;
public static DataRow dtrow;
public static DataTable lbdt;
public static DataTable sqldt;
public static string ID;
private static FormWorkers _main = new FormWorkers();
public static FormWorkers Main {
get {
return _main;
}
}
public void load_List() {
string connStr = @"Data Source=.\SQLEXPRESS_KEVIN;Database=Test;Integrated Security=true";
using (SqlConnection conn = new SqlConnection(connStr)) {
using (SqlDataAdapter sqlSelect = new SqlDataAdapter("SELECT Emp_ID,Name FROM Employees INNER JOIN Accounts ON Employees.Acct_ID=Accounts.Acct_ID WHERE Emp_ID >= 1", conn)) {
lbdt = new DataTable();
sqlSelect.Fill(lbdt);
dtrow = null;
}
}
}
public void load_Db() {
try {
string connStr = @"Data Source=.\SQLEXPRESS_KEVIN;Database=Test;Integrated Security=true";
using (SqlConnection conn = new SqlConnection(connStr)) {
using (sqlSelect = new SqlDataAdapter("SELECT Emp_ID AS 'ID',Accounts.Name,Emp_Address AS 'Address',Emp_Contact AS 'Phone',Emp_Email AS 'Email',Emp_FName,Emp_MName,Emp_LName,Username,Type FROM Employees INNER JOIN Accounts ON Employees.Acct_ID=Accounts.Acct_ID", conn)) {
sqldt = new DataTable();
sqlSelect.Fill(sqldt);
}
}
} catch (SqlException err) {
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public void insert_Record(string FullName, string Username, string Password, string Type, string FirstName, string MInitial, string LastName, string Address, string Phone, string Email) {
try {
string connStr = @"Data Source=.\SQLEXPRESS_KEVIN;Database=Test;Integrated Security=true";
using (SqlConnection conn = new SqlConnection(connStr)) {
using (sqlInsert = new SqlCommand(
"INSERT INTO Accounts (Name,Username,Password,Type) VALUES (@name,@username,@password,@type);" +
"INSERT INTO Employees (Acct_ID,Emp_FName,Emp_MName,Emp_LName,Emp_Address,Emp_Contact,Emp_Email) " +
"SELECT TOP 1 Acct_ID,@FName,@MName,@LName,@Address,@Phone,@Email FROM Accounts ORDER BY Acct_ID DESC", conn)) {
sqlInsert.Parameters.AddWithValue("@name", FullName);
sqlInsert.Parameters.AddWithValue("@username", Username);
sqlInsert.Parameters.AddWithValue("@password", Password);
sqlInsert.Parameters.AddWithValue("@type", Type);
sqlInsert.Parameters.AddWithValue("@FName", FirstName);
sqlInsert.Parameters.AddWithValue("@MName", MInitial);
sqlInsert.Parameters.AddWithValue("@LName", LastName);
sqlInsert.Parameters.AddWithValue("@Address", Address);
sqlInsert.Parameters.AddWithValue("@Phone", Phone);
sqlInsert.Parameters.AddWithValue("@Email", Email);
conn.Open();
sqlInsert.ExecuteNonQuery();
}
}
} catch (SqlException err) {
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public void update_Info(string Emp_ID, string FullName, string Password, string Type, string FirstName, string MInitial, string LastName, string Address, string Phone, string Email) {
try {
string connStr = @"Data Source=.\SQLEXPRESS_KEVIN;Database=Test;Integrated Security=true";
using (SqlConnection conn = new SqlConnection(connStr)) {
conn.Open();
using (sqlUpdate = new SqlCommand(
"UPDATE Accounts SET Name=@name,Password=@password,Type=@type FROM Accounts INNER JOIN Employees ON Accounts.Acct_ID=Employees.Acct_ID WHERE Emp_ID=@Emp_ID;" +
"UPDATE Employees SET Emp_FName=@FName,Emp_MName=@MName,Emp_LName=@LName,Emp_Address=@Address,Emp_Contact=@Phone,Emp_Email=@Email WHERE Emp_ID=@Emp_ID", conn)) {
sqlUpdate.Parameters.AddWithValue("@name", FullName);
sqlUpdate.Parameters.AddWithValue("@password", Password);
sqlUpdate.Parameters.AddWithValue("@type", Type);
sqlUpdate.Parameters.AddWithValue("@FName", FirstName);
sqlUpdate.Parameters.AddWithValue("@MName", MInitial);
sqlUpdate.Parameters.AddWithValue("@LName", LastName);
sqlUpdate.Parameters.AddWithValue("@Address", Address);
sqlUpdate.Parameters.AddWithValue("@Phone", Phone);
sqlUpdate.Parameters.AddWithValue("@Email", Email);
sqlUpdate.Parameters.AddWithValue("@Emp_ID", Emp_ID);
sqlUpdate.ExecuteNonQuery();
}
}
} catch (SqlException err) {
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void delete_Record(string Emp_ID) {
try {
string connStr = @"Data Source=.\SQLEXPRESS_KEVIN;Database=Test;Integrated Security=true";
using (SqlConnection conn = new SqlConnection(connStr)) {
using (sqlDelete = new SqlCommand(
"DELETE Accounts FROM Accounts INNER JOIN Employees ON Accounts.Acct_ID=Employees.Acct_ID WHERE Emp_ID=@ID;" +
"DELETE FROM Employees WHERE Emp_ID=@ID", conn)) {
sqlDelete.Parameters.AddWithValue("@ID", Emp_ID);
conn.Open();
sqlDelete.ExecuteNonQuery();
}
}
} catch (SqlException err) {
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
|
|
|
|
|
We aren't here to mark your homework!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
You're storing passwords in plain text. That's an immediate security failure. You should only ever store a salted hash of the password, using a unique salt per record.
Secure Password Authentication Explained Simply[^]
Salted Password Hashing - Doing it Right[^]
You've repeated the connection string in every method. You should move that to a field on the class, or better yet, store it in the application's configuration file.
You should remove all of the fields currently on your FormWorkers class, and use local variables and return values instead. As it stands, your code is not thread-safe.
You should make all of the methods in the FormWorkers class static , and mark the class itself as static . That way, you won't need to keep creating instances of the class to call the methods.
On the plus side, you have correctly parameterised your queries, avoiding SQL Injection vulnerabilities.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Message Closed
modified 7-Feb-17 6:52am.
|
|
|
|
|
The main difference is that Array is fixed size, while an ArrayList will grow as required. If you know the required size of a collection of objects, then Array is the best solution. If you are adding items to it indeterminately, then the ArrayList is the way to go.
Cheers,
Mick
------------------------------------------------
It doesn't matter how often or hard you fall on your arse, eventually you'll roll over and land on your feet.
|
|
|
|
|
Oh, I forget that point thanks to remind me dear
|
|
|
|
|