|
Hi. I would like to validate a textbox so that it only contains strings (words/sentences) but not symbols such as < > ! @ etc.
I checked the Regular Expression Validator, but didnt find a Validation Expression which validates for symbols
Is there a Validator Expression for this? Thanks
|
|
|
|
|
You just need a Regex[^] that matches on alphabetic characters, plus any acceptable punctuation such as period, comma, space etc.
Use the best guess
|
|
|
|
|
Accessing methods of a derived class that are not in base class. I suppose there is a trick related to Implementation of Generics to achieve this. Can somebody brief the trick or defend if its not possible.
|
|
|
|
|
No. A Base class cannot (under normal circumstances) access methods of a derived class unless they are implemented in the base class and overridden. Think about it:
public class Base
{
public virtual void Method()
{
Console.WriteLine("Base");
}
}
public class DerivedA : Base
{
public override void Method()
{
Console.WriteLine("A");
}
}
public class DerivedB : Base
{
public override void Method()
{
Console.WriteLine("B");
}
public void OtherMethod()
{
Console.WriteLine("Other method");
}
}
public class DerivedC : Base
{
public void OtherMethod()
{
Console.WriteLine("Other method");
}
}
Base can access Method in any class instance, because there will always be a Method, even if it is the base class implementation.
But it can't access OtherMethod, because it is not defined to exist in derived classes - and doesn't in DerivedA.
The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)
|
|
|
|
|
It might be possible to do this via reflecion, I don't know, I haven't tried.
But I've had a good reason for not trying. By doing this you are creating a dependency from the base class to the derived class meaning the method will most likely go wrong if you call the base class's method from a different subtype. The likelihood is that your hierarchy is wrong:- either you need to declare the necessary method in the base type anyway, or you require a third type (probably between the existing two).
If you give us the reason why you want to do this, then we might be able to provide further help.
“Education is not the piling on of learning, information, data, facts, skills, or abilities - that's training or instruction - but is rather making visible what is hidden as a seed” “One of the greatest problems of our time is that many are schooled but few are educated”
Sir Thomas More (1478 – 1535)
|
|
|
|
|
Hi,
When your base class requires an implemented method from a derived class, you can make the method abstract. This means all derived classed have the responsibility of implementing that method and that the base class may call it.
Not sure what you mean by "I suppose there is a trick related to Implementation of Generics to achieve this.".
Kind Regards,
Keld Ølykke
|
|
|
|
|
The "trick" is to go do some research and teach yourself how Object Oriented Programming really works.
There is no special "trick" and Generics have nothing to do with this at all.
|
|
|
|
|
Public methods? Or private/internal/protected?
Similar to Keld's suggestion you can do:
public abstract class MyBase
{
public virtual void DoSomeThing()
{
DoStep1();
DoStep2();
}
protected abstract void DoStep1();
protected abstract void DoStep2();
}
public class Derived : MyBase
{
override void DoStep1()
{
}
override void DoStep2()
{
SomeOtherMethod();
}
private void SomeOtherMethod()
{
}
}
When you call the DoSomeThing() method of the "base" class, the DoStep1() , DoStep2() , and SomeOtherMethod() functions of Derived are called.
Well, actually, you do not call DoSomeThing() of MyBase , but DoSomeThing() of Derived , which was inherited from MyBase .
See also: Template Method[^]
|
|
|
|
|
|
Please note that your link goes to a performance optimization of the template pattern.
It is to performance optimize pure virtual functions (aka abstract methods) in classes.
My C++ is a bit rusty, so I am not sure why the move of the pure virtual function from .cpp to .h also made it change visibility from protected to public. If this is required for the performance optimization to work then this technique trades encapsulation (do you want to allow externals to call Process?) for better performance.
Any C++ person here to confirm this point?
Kind Regards,
Keld Ølykke
|
|
|
|
|
What you probably want to do is define an empty virtual method in the base class, thereby allowing derived classes to override. it. The base class simply calls this method. At run time, the derived class' method (if it is defined) will be called.
/ravi
|
|
|
|
|
hi all, its my first time here...i am writing an app that will receive voice from a Huawei E1752 modem, save it as a wav file and the file is later accessed by the speech SDK for processing. i have inquired from Google(my best friend) and also from past articles on this site and i am able to save something to the wav file but its not really the voice i expect to be saved, and when the speech SDK accesses the file, it brings an error saying (the audio file is not a recognizable format). how can i save the audio from the modem to a format that can be recognized by the speech sdk. i have been able to write this
thanks.
namespace joaninne
{
public partial class Form1 : Form
{
static SerialPort _SerialPort1;
byte[] buffer;
FileStream file;
public Form1()
{
InitializeComponent();
file = File.Open(@"D:\speechtestfiles.wav", FileMode.Create);
_SerialPort1 = new SerialPort("COM31", 9600, Parity.None, 8, StopBits.One);
_SerialPort1.DtrEnable = true;
_SerialPort1.RtsEnable = true;
_SerialPort1.ReadTimeout = SerialPort.InfiniteTimeout;
_SerialPort1.Open();
_SerialPort1.Write("ATS0=1\r");
buffer = new byte[100 * 1024];
_SerialPort1.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
Thread.Sleep(1000);
_SerialPort1.Close();
file.Close();
file.Dispose();
using (SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine(new CultureInfo("en-US")))
{
Choices appliances = new Choices(new string[] { "fan", "lights" });
Choices Commands = new Choices(new string[] { "on", "off" });
GrammarBuilder gb = new GrammarBuilder();
gb.Append("Please turn the");
gb.Append(appliances);
gb.Append(Commands);
Grammar g = new Grammar(gb);
recognizer.LoadGrammarAsync(g);
recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
recognizer.SpeechRecognitionRejected +=
new EventHandler<SpeechRecognitionRejectedEventArgs>(recognizer_SpeechRecognitionRejected);
var isReady = false;
while (!isReady)
{
isReady = IsFileReady(@"D:\speechtestfiles.wav");
}
recognizer.SetInputToWaveFile(@"D:\speechtestfiles.wav");
recognizer.RecognizeAsync(RecognizeMode.Multiple);
}
}
private void sp_DataReceived(object Sender, SerialDataReceivedEventArgs e)
{
int x = _SerialPort1.BytesToRead;
_SerialPort1.Read(buffer, 0, x);
file.Write(buffer, 0, x);
}
public static bool IsFileReady(String file)
{
try
{
using (FileStream inputStream=File.Open(file,FileMode.Open,FileAccess.Read,FileShare.None))
{
if (inputStream.Length>0)
{
return true;
}
else
{
return false;
}
}
}
catch (Exception)
{
return false;
}
}
public static void recognizer_SpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e)
{
foreach (RecognizedPhrase phrase in e.Result.Alternates)
{
Console.WriteLine(" Rejected phrase: " + phrase.Text);
}
}
public static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
string _detected = (e.Result.Text);
string _recognised1 = " Please turn the lights on";
if (String.Compare(_recognised1, _detected) == 0)
{
PortAccess.Output(888, 1);
}
else
{
}
}
}
}
|
|
|
|
|
samweps wrote:
FileStream file; Writing a sequence of bytes to a FileStream does not produce a .wav file. You need to research how to create the sound file in the correct format[^].
Use the best guess
|
|
|
|
|
I'm doing some long term tests on my driver and have experienced an error relatively quickly; after only 23 hours of opperation, my log shows the following error:-
System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host
Now, does this mean that my instrument for some reason dropped the connection or could it perhaps mean that 'the network' has misbehaved ?
I guess I should add a method to try and re-establish the connection when this kind of exception is thrown but any thoughts anybody has would be welcome. Others must have experienced this kind of thing too; I will wire shark the connection in a moment to see If I can glean anything more because I can ping the instrument and get timely replies..
UPDATE______________________________________________________
Ok so:- This problem was the result of the laptop having gone to sleep. I have disabled any chance of it getting it's head down in the future ! Thanks for your thoughts though..
modified 21-May-13 11:45am.
|
|
|
|
|
Member 9862872 wrote: System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host Check out this[^] kb-article, and verify that WPA is not the cause.
Member 9862872 wrote: Now, does this mean that my instrument for some reason dropped the connection or could it perhaps mean that 'the network' has misbehaved ? It means that the server closed the socket, and gave that code as a reason.
What port are you on? Any other apps using that port? What kind of server is the TCP-server?
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Hello,
Looking for some help in case of generics comparison:
I'm using a derived Type inside a Generic. This would be generated at run time, and so, I have to compare only the object type as shown below (in the IF Condition):
The Project Structure is as shown below:
class ClassType
{
}
class IByte:ClassType
{
}
class IInt:ClassType
{
}
class Class1<T> where T:ClassTpe
{
}
public class MainClass
{
public MainClass()
{
Class1<IByte> str = new Class1<IByte>();
Class1<IInt> insd = new Class1<IInt>();
if (insd is Class1) //NEED HELP TO IMPLEMENT THIS
{
}
}
}
-- modified 21-May-13 5:50am.
|
|
|
|
|
Try if (insd.GetType() is Class1.GetType())
|
|
|
|
|
Hello Abhinav
the point is we cannot use "Class1.getType()" It asks for the generic type like.. we must specify - Class1<type>.getType(0 instead. This is the problem I'm struck.
|
|
|
|
|
I can think of two ways to solve this problem. In the first the generic type definition is extracted from the object (see GenericTypeDefinition method in the example) and tested against actual definition e.g. typeof(Class1<>) .
In the second, which I prefer (see Class2 in the example), the generic class must inherit a non generic abstract base class. Any Class2<T> may then be tested against the base class using the is operator.
namespace GenericTypeTest {
class Class1<T> { }
abstract class BaseClass { }
class Class2<T> : BaseClass { }
internal class App {
static void Main() {
IsClass1(new Class1<int>());
IsClass1(new Class1<string>());
IsClass1(new Class2<string>());
IsClass1(42);
IsClass1("Tiger");
Class2<string> strObj = new Class2<string>();
if (strObj is BaseClass) {
Console.WriteLine("{0} is derived from BaseClass", strObj);
}
Console.ReadLine();
}
static void IsClass1(Object obj) {
if (GenericTypeDefinition(obj) == typeof(Class1<>)) {
Console.WriteLine("{0} was constructed from {1}", obj.GetType(), typeof(Class1<>));
} else {
Console.WriteLine("{0} was NOT constructed from {1}", obj.GetType(), typeof(Class1<>));
}
Console.WriteLine();
}
static Type GenericTypeDefinition(Object obj) {
Type result = null;
Type test = obj.GetType();
if (test.IsGenericType && !test.IsGenericTypeDefinition) {
result = test.GetGenericTypeDefinition();
}
return result;
}
}
}
|
|
|
|
|
Thanks a lot Alan, This approach has resolved my issue!
|
|
|
|
|
You can do this:
if (insd.GetType() is Class1<IByte>) {} But, using a temporary variable and the "as" operator is more performant than using "is," and will not throw an error:
Class1<IInt> testObject = insd as Class1<IInt>;
if (testObject != null) Console.WriteLine("it's Class1<int>"); Is your goal here to test an "unknown" object's type at run-time, and then take action based on the underlying type? If so, there are other strategies you can use.
yours, Bill
“Humans are amphibians: half spirit, half animal; as spirits they belong to the eternal world; as animals they inhabit time. While their spirit can be directed to an eternal object, their bodies, passions, and imagination are in continual change, for to be in time, means to change. Their nearest approach to constancy is undulation: repeated return to a level from which they repeatedly fall back, a series of troughs and peaks.” C.S. Lewis
|
|
|
|
|
Hi All,
I am trying to create a function that passes the cursor's starting and ending x,y coordinates as parameters. For instance I would like to set the cursor's starting x,y coordinate when the user clicks the left mouse button. Then as the user holds down the left mouse button and drags the cursor to a desired location, the ending x,y coordinate is dynamically set and updated. The final ending coordinate is set when the left button is released. I am currently working with the following code:
private void Cursor_Coord(out Cursor C1, out Cursor C2)
{
Cursor C1;
Cursor C2;
if(Mouse.LeftButton == MouseButtonState.Pressed)
{
C1 = new Cursor(Cursor.Current.Handle);
C1.Position = new Point(Cursor.Position.X, Cursor.Position.Y);
}
if(Mouse.LeftButton == MouseButtonState.Released)
{
C2 = new Cursor(Cursor.Current.Handle);
C2.Position = new Point(Cursor.Position.X, Cursor.Position.Y);
}
}
I am planning to send the changing cursor coordinates to the Drawline method to be used as the first and second point. The effect I have in mind is that the line is drawn as the mouse is in motion. The problem is it's not working. Any help will be greatly appreciated, thanks in advance.
modified 21-May-13 4:02am.
|
|
|
|
|
You don't need to use a cursor to do this. As you've rightly noted in your code, the part you are actually interested in is the Position - that's all you need to keep track of.
|
|
|
|
|
Hi, you've replied to my post as I was in the process of making changes to it.
|
|
|
|
|
This is pretty easy to do, but I think you are trying to do it the wrong way. You don't say what your environment is, but I'll assume WinForms.
First off, you probably don't need to use Cursor at all for this, a simple Point is enough.
Try doing this by adding a few class level variables, and handling a few events:
private Point pointStart;
private Point pointEnd;
private bool drawing = false;
private void frmMain_MouseDown(object sender, MouseEventArgs e)
{
pointStart = e.Location;
pointEnd = pointStart;
drawing = true;
Invalidate();
}
private void frmMain_MouseUp(object sender, MouseEventArgs e)
{
drawing = false;
}
private void frmMain_MouseMove(object sender, MouseEventArgs e)
{
if (drawing)
{
pointEnd = e.Location;
Invalidate();
}
}
private void frmMain_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawLine(Pens.Blue, pointStart, pointEnd);
}
The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)
|
|
|
|
|