|
If you are using C#6, try this instead:
public class AccessIOPortException : Exception
{
public AccessIOPortException(string message, int port) : base($"Error accessing port {port}{Environment.NewLine}{message}")
{
Port = port;
}
public int Port { get; }
}
This space for rent
|
|
|
|
|
What's "wrong" with this is that you are not "throwing" your new exception; you're simply creating an instance of the exception and passing it around.
If you throw your new exception, it will become the "inner" exception of any later exception handling, if any; otherwise, it is "the" exception.
Exception.InnerException Property (System)
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
For any real exception, you'll need to make it serializable.
You should also have a constructor which accepts the inner exception, if there is one.
[Serializable]
public class AccessIOPortException : Exception
{
public AccessIOPortException(string message, int port, Exception innerException) : base(FormatMessage(message, port), innerException)
{
Port = port;
}
public AccessIOPortException(string message, int port) : base(FormatMessage(message, port))
{
Port = port;
}
protected AccessIOPortException(SerializationInfo info, StreamingContext context) : base(info, context)
{
Port = info.GetInt32(nameof(Port));
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue(nameof(Port), Port);
}
private static string FormatMessage(string message, int port)
{
return $"Error while accessing IO port {port}\n{message}";
}
public int Port { get; }
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I would find an article explaining this code very valuable, and I think many others would also benefit.
thanks, Bill
«There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008
|
|
|
|
|
Hi I am new to c# and learning a lot lately. My question relates to classes. Say I create a class then fill it with my parameters and a constructor, do I need a method for functionality in the class or do classes not always need functionality. Just a general question.
|
|
|
|
|
Are you asking this more from a language-lawyer point of view (having no methods is of course allowed by the language) or more from a design point of view, eg how useful is a class with no methods?
|
|
|
|
|
Properties are kinda like methods. A class could be nothing more than a data bag. He could use a struct instead, but why bother?
".45 ACP - because shooting twice is just silly" - JSOP, 2010
- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
Depends on what you are storing in the struct, and what you are doing with it.
Using struct and class - what's that all about?[^] explains it, I think (even if it is blowing my own trumpet).
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
The only hard and fast rules as far as what to use are enforced by the compiler. Everything else are just guidelines.
".45 ACP - because shooting twice is just silly" - JSOP, 2010
- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
A class does not even need an (explicit) constructor. Any data members of such a class will be initialized with the default value for their type. If you make all the data members 'public', you may access them by name.
However, writing classes this way is IMO an abuse of the language. Just because it can be done does not mean that it should be done.
As usual, every rule has its exceptions; there are some cases when this is just what you need.
If you have an important point to make, don't try to be subtle or clever. Use a pile driver. Hit the point once. Then come back and hit it again. Then hit it a third time - a tremendous whack.
--Winston Churchill
|
|
|
|
|
Classes don't always need methods. Suppose that you have a data model that represents a user.
public class Name
{
public string Name { get; set; }
public int Department { get; set; }
public DateTime BirthDate { get; set; }
} This model is perfectly fine. It's generally considered good practice to separate out the retrieving of the data from the model, so you might have a separate class that is responsible for retrieving the data and populating the name*. That might look something like this:
public class Users
{
private IEnumerable<User> users;
public IEnumerable<User> Users { get { return users; } }
public void LoadUsers()
{
users = new List<User>();
using (DataAccess dal = new DataAccess())
{
IDataReader reader = dal.GetValuesFromStoredProcedure("GetUsers");
while (reader.Read())
{
User user = new User();
dal.Populate(user.Name, "Name");
dal.Populate(user.Department, "Department");
dal.Populate(user.BirthDate, "DOB");
users.Add(user);
}
}
}
} A little bit of explanation about that last method before you get worried. DataAccess is the name of a class I have that allows me to do a lot of common SQL data operations - I prefer having my own version, rather than relying on things like Entity Framework. The methods you see being called in there are responsible for retrieving values from a stored procedure, then using that to populate a list of users.
*I meant to add this earlier. Even though the data model class doesn't visibly have methods because you have exposed properties here, the internal code that is created from this has methods because a property internally translates to separate get and set methods; so, Name becomes get_Name() and set_Name(string value) internally.
This space for rent
modified 11-Jan-17 6:07am.
|
|
|
|
|
You don't need to create "methods" for your new class; though you will always have some by default because every class ultimately inherits from class "Object"; and "object" has a few built-in methods like ToString() and GetType().
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
Hi all,
How to multiple tabs open and close click on buttons.
Actually i want to this scenario :
1.Dynamically add some tab items in browser [ Click on Add button ]
2.Dynamically close all browser tab items ,still open remaining single tab item.[ Click on Close button]
How its possible in Java Script or C#.
Thanks,
A.Aniruddhan
|
|
|
|
|
Aniruddha.A wrote: 1.Dynamically add some tab items in browser
<a href="/path.html" target="_blank">Click me</a>
This code will open the content in a new tab. As for JavaScript, you cannot open a new tab because that is user preference and he gets to do that, such as CTRL + Click. JavaScript gets to open a new tab only, unless a browser-specific feature allows such,
var win = window.open('www.google.com', '_blank');
win.focus();
Code from: http://stackoverflow.com/a/11384018/1762944, but browser can still control this.
Aniruddha.A wrote: .Dynamically close all browser tab items ,still open remaining single tab item.
As mentioned earlier, you do not get to chose this, unless you control the browser-specific API such as Chrome API for tabs — chrome.tabs - Google Chrome and you would then have an extension in the browser that does all of this — and is still not possible through a web application. If you want to create an extension for this, you can refer that documentation I provided and learn how to manage the tabs from your extension. Extensions can have buttons that you can use.
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
Hi
I have been successfully using Lev's assembly for extracting EXIF data from my jpeg photos. I am particularly interested in the GPS data. Unfortunately I get an error when trying to use the code on Adobe DNG files. Can anyone tell me if a more recent source file is available which supports DNG files?
Best
Grahame
|
|
|
|
|
As you are asking about an article from a member who doesn't look to be active here any more, I would suggest that you look for an alternative to this library. You might find something that suits you here[^].
This space for rent
|
|
|
|
|
Thanks Pete. I had a brief look and though it doesn't explicity mention DNG files, I will further investigate. Thank you!
Grahame
|
|
|
|
|
With the author being active, you stand a much better chance of there being enhancements.
This space for rent
|
|
|
|
|
Using VS2015.
I'm trying to write some code that gives a list a solutions, and when clicked, opens that solution in the CURRENT instance of VS.
So far I have this:
public static class AutomateVS
{
[DllImport("ole32.dll")]
private static extern int CreateBindCtx(uint reserved, out IBindCtx ppbc);
public static DTE GetDTE(int processId)
{
string progId = "!VisualStudio.DTE.14.0:" + processId.ToString();
object runningObject = null;
IBindCtx bindCtx = null;
IRunningObjectTable rot = null;
IEnumMoniker enumMonikers = null;
try
{
Marshal.ThrowExceptionForHR(CreateBindCtx(reserved: 0, ppbc: out bindCtx));
bindCtx.GetRunningObjectTable(out rot);
rot.EnumRunning(out enumMonikers);
IMoniker[] moniker = new IMoniker[1];
IntPtr numberFetched = IntPtr.Zero;
while (enumMonikers.Next(1, moniker, numberFetched) == 0)
{
IMoniker runningObjectMoniker = moniker[0];
string name = null;
try
{
if (runningObjectMoniker != null)
{
runningObjectMoniker.GetDisplayName(bindCtx, null, out name);
}
}
catch (UnauthorizedAccessException)
{
}
if (!string.IsNullOrEmpty(name) && name.Contains("!VisualStudio.DTE.14.0:"))
{
rot.GetObject(runningObjectMoniker, out runningObject);
break;
}
if (!string.IsNullOrEmpty(name) && string.Equals(name, progId, StringComparison.Ordinal))
{
Marshal.ThrowExceptionForHR(rot.GetObject(runningObjectMoniker, out runningObject));
break;
}
}
}
finally
{
if (enumMonikers != null)
{
Marshal.ReleaseComObject(enumMonikers);
}
if (rot != null)
{
Marshal.ReleaseComObject(rot);
}
if (bindCtx != null)
{
Marshal.ReleaseComObject(bindCtx);
}
}
return (DTE)runningObject;
}
}
}
and use it like this
var process = System.Diagnostics.Process.GetCurrentProcess();
var id = process.Id;
_envDTE = AutomateVS.GetDTE(id);
if (_envDTE != null)
{
_envDTE.Solution.Open(solutionFile);
}
But it opens in the wrong VS instance. I need it to open in the instance my app is running in.
Anyone know what's wrong?
Thanks
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
Kevin Marois wrote: But it opens in the wrong VS instance. I need it to open in the instance my app is running in. In the wrong instance or in a new instance? Because that is what happens, if you even double click a new file to be opened in Visual Studio.
To open a file in a specific version you would require to have a Visual Studio extension, that communicates with Visual Studio to know where to load the file and then it will load the file there.
If you are interested in Visual Studio extensions, go to this link and get to know how you can develop a simple extension that does this for you.
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
I created program where when user checks checkbox edit text is enabled, but when I check any of checkboxes nothing happens!!!
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText2 = (EditText) findViewById(R.id.editText_symbols);
editText3 = (EditText) findViewById(R.id.editText_numbers);
editText4 = (EditText) findViewById(R.id.editText_lowercase);
editText5 = (EditText) findViewById(R.id.editText_uppercase);
editText2.setEnabled(false);
editText3.setEnabled(false);
editText4.setEnabled(false);
editText5.setEnabled(false);
}
public void checkCheckBox(View view)
{
boolean checked = (((CheckBox)view).isChecked());
switch (view.getId())
{
case R.id.checkBox_uppercase:
if(checked)
editText2.setEnabled(true);
else
editText2.setEnabled(false);
break;
case R.id.checkBox_lowercase:
if(checked)
editText3.setEnabled(true);
else
editText3.setEnabled(false);
break;
case R.id.checkBox_numbers:
if(checked)
editText4.setEnabled(true);
else
editText4.setEnabled(false);
break;
case R.id.checkBox_symbols:
if(checked)
editText5.setEnabled(true);
else
editText5.setEnabled(false);
break;
}
}
|
|
|
|
|
Pavlex4 wrote: nothing happens
Maybe because this is not C#?
Speed of sound - 1100 ft/sec
Speed of light - 186,000 mi/sec
Speed of stupid - instantaneous.
|
|
|
|
|
Instead of flooding these forums with every issue you face, why not try to do some actual debugging of your code first? Also, the above code is not C#, it is Android Java.
|
|
|
|
|
How to do this in Java Android Development?
var _pass = new string(
Enumerable.Repeat(_chars, _len)
.Select(s => s[_rnd.Next(s.Length)])
.ToArray());
modified 8-Jan-17 10:38am.
|
|
|
|
|
First, learn Java.
Second, learn C#.
Then translate the one to the other.
We are not here to do your work for you. And since you are clearly trying to get by without thinking for yourself - your other questions are clear evidence of that - I for one am not prepared to do any more for you. Pull your finger out, learn your subject(s) and start thinking.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|