spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
  Home » C# » Page 4
Different behavior of exception with async method
There's no difference in the exception handling required for both SomeMethod1 and SomeMethod2. They run exactly the same way and the exception would be stored in the returned task. This can easily be seen in this example; static void Main(string[] args) { try { var task = SomeMethod1(); } catch { // Unreachable code } } public static async Task SomeMethod

Categories : C#

c# Object Comparison fails
1- Why this happens ? Because you are not comparing values of the variables, but their references. Since both variables are object, == calls Object.ReferenceEquals. 2- How can I do to compare those values to get the right answer ? If both types are string, cast them and compare them as strings. string a = ColumnaOrigen.Properties["DataType"].Value as string; string b = ColumnaDestino.P

Categories : C#

ClickOnce Manifest has invalid children - but xml matches old published manifests
clickonce has it's own headaches. especially if you make any changes to the manifest. What has proven to me to be the best workflow, when making changes to the manifest, turn of VS then start it, clean the project, build, restart VS, clean rebuild. After publishing the new clickonce package, do NOT change anything in the folder. DO NOT add, delete or update anything. as soon as you change anything

Categories : C#

SystemOutOfMemory Exception When Loading .JPG's
Directory.GetFiles loads all file names into memory. You can use EnumerateFiles if you don't need all of them: foreach(var file in Directory.EnumerateFiles(picturesPath, "*", SearchOption.AllDirectories)) Or via LINQ you can make it more cleaner: var images = Directory.EnumerateFiles(picturesPath, "*", SearchOption.AllDirectories) .Where(f => Path.GetExtension(f) == ".png" || Path.G

Categories : C#

C# Basic Calculator SharpDevelop Error
The calculation method is an integer and you are not returning anything public int Calculation (int number) { int Store = number * number; Console.WriteLine ("This is the square of your number : {0}" , Store); return Store; // Needed }

Categories : C#

Type parameter conversion between IEntity and IComparable
i spuspect that it should be some implicit operator but there is no way to cast between those 2 interfaces public static implicit operator IEquatable<T> (IComparable<T> obj) { return ???; } maybe you can try extends IEntity to implement IEquatable as well public interface IEntity where T : IComparable, IEquatable

Categories : C#

How can I reliably test/benchmark the size (including empty buckets) of a .Net HashSet object?
thst is interesting questionstrong text... i have a radical suggestion for you: start your application and get the size of memory before initializing the HashSet. you can do so by using Process.GetCurrentProcess().WorkingSet64 (on msdn: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.workingset64(v=vs.110).aspx) then populate your HashSet and print Process.GetCurrentProcess().

Categories : C#

How to handle null exception when converting from object to string?
This is an boxing / unboxing issue. 20.09089 is a double by default. When you wanna unbox a primitive type from object, you need to unbox it the original type first. Object obj = new object(); obj = 20.09089; string value = ((double)obj).ToString(); or simplify; Object obj = new object(); obj = 20.09089; string value = obj.ToString();

Categories : C#

Ensure executable run by Process from a thread is terminated when Application Exits
I figured better way to solve this problem, using the class destructor itself. I tested running more than 10 ping processes simultaneously, closing the application killed all of them :-) Using a thread to run the process allowed the application to be responsive while the process(s) being run.. // Example of ShowOutput and ShowError that will be used in Form1.cs //void ShowOutput(

Categories : C#

Word add-in DocumentBeforeClose event only firing once
The event handler you register is on one specific document. If you close it, the event handler doesn't count for subsequent documents. If you don't want the BeforeClose event fire for one specific document, but for any document that gets opened, use the Application.DocumentBeforeClose event. Globals.ThisAddIn.Application.DocumentBeforeClose += Application_DocumentBeforeClose; void Application_D

Categories : C#

How to convert xml string to an object using c#
if you want to avoid serialization, as you only want a very specific part of the xml, you can do this with one LINQ statement: var items = XDocument.Parse(xml) .Descendants("E") .Select(e => new { Name = e.Attribute("NAME").Value, Email = e.Attribute("EMAIL").Value }) .ToList()

Categories : C#

Encoding JSON serialized for URL
@Ant P is correct: you want those characters to be encoded. It is a bad idea not to encode them. HttpUtility.UrlEncode and other similar methods encode {, } and : because they MUST do so per section 2.2 of the Uniform Resource Locators specification (RFC 1738). From page 2: Octets [within a URL] must be encoded if they have no corresponding graphic character within the US-ASCII coded c

Categories : C#

Pinvoke Bool - MarshalDirectiveExeption
As the error says, the struct is not p/invoke compatible. Function return values must be blittable and that type is not. The information can be found here: http://msdn.microsoft.com/en-us/library/75dwhxf7.aspx Structures that are returned from platform invoke calls must be blittable types. Platform invoke does not support non-blittable structures as return types. That same topic goes on to l

Categories : C#

Get fully-qualified metadata name in Roslyn
For now, having no better solution, I'm using the following: public static string GetFullMetadataName(this INamespaceOrTypeSymbol symbol) { ISymbol s = symbol; var sb = new StringBuilder(s.MetadataName); var last = s; s = s.ContainingSymbol; while (!IsRootNamespace(s)) { if (s is ITypeSymbol && last is ITypeSymbol) { sb.Insert(0, '+'); } else { sb.Insert(0,

Categories : C#

Call C method in C# by DllImport - attempt to read or write protected memory
call_sb_kernel expects two pointers, not structures. Change your definition to ref InArg inArg, out OutArg outArg and use it like call_sb_kernel_std(0, ref inArg, out outArg);.

Categories : C#

Mutliple authorizations in a single browser in ASP.NET MVC
The default behavior is to store the authorization cookie and use Session, so it's not possible with the default behavior. To do this you will need another way to store authorization data and track authorization

Categories : C#

How can I use regex expression to match database and table name given in textbox
How about this: You were close. You need to escape the square brackets. Debuggex Sample [(.+?)]

Categories : C#

Not Inserting values in Table
I think you forget to set your CommandType property and your program thinks your "AddingPagesInGrid" as a Text which is the default value of a CommandType. Just add; cmd.CommandType = CommandType.StoredProcedure; And use using statement to dispose your SqlConnection and SqlCommand. using(SqlConnection conn = new SqlConnection(conString)) using(SqlCommand cmd = conn.CreateCommand()) { } An

Categories : C#

Triggering an event in c# from c++ and declaring LPCWSTR
Your code doesn't show the critical call to GpioSetupInterruptPin. That said, I think you're over-complicating it. Just define it as a string and be done with it. Also, I'm not seeing you creating a named system event in your code. The event handlers, etc. that you posted are not at all relevant to the problem. What you need to do is P/Invoke CreateEvent with the same string name you pass to

Categories : C#

How to expose a method to setup a member in a large class?
Not best idea to design you interaction with DB by that way. But if you want: public class Class { private string p1; private int p2; private decimal p3; public void SetPi<T>(string name, T value) { var field = this.GetType().GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); if (field == null) throw new Arg

Categories : C#

Using Inner Join in FilterClause
You can implement essentially the same logic using IN with a subquery in the WHERE clause. Does this work for you? SELECT * FROM dbo.table_a WHERE table_a.num_id IN (SELECT num_id FROM dbo.link_table_ab WHERE link_table_ab.b_index = 5 )

Categories : C#

Remove on custom HashSet
A HashSet is not a list or array, it has no indexer and you cannot access an item via index. The reason is that the order is not guaranteed (if you never remove any items, it will preserve insertion order in the current implementation). If that doesn't matter you can use ElementAtOrDefault: User fifth = users.ElementAtOrDefault(4); if (fifth != null) users.Remove(fifth); Does HashSet preserve

Categories : C#

How can I compare different date values
If this is a DateTime value, you can use .AddDays() method and compare with < and > operators. if(yourDateTime < DateTime.UtcNow.AddDays(-1)) { // do something. } If this is a string value, you can use custom date and time formatting and compare with < and > operators. string s = "201411241440"; DateTime dt; if(DateTime.TryParseExact(s, "yyyyMMddHHmm",

Categories : C#

How to preserve null in system.array - C#?
From looking at what you are doing Cast would be more appropriate than OfType. List<object> Array = myvalues.Cast<object>().ToList(); This should do what you want and basically just tell it that all objects should be cast to type object. This will preserve the null. The reason for the difference is that OfType does a check for current is TResult before returning the cast object and

Categories : C#

Create new object in win 8 store app
Here, study this simple example to get hold of MVVM/DataBinding/Commands. It's really simplistic but it should show the "patterns" to use. There's plenty of libs (like MVVMLight) to make commanding etc. simpler and more powerful. So assuming we have Place entity public class Place { public int Id { get; set; } public string Title { get; set; } public string Description { get; set; }

Categories : C#

Parse text file into dictionary C#
Your dictionary is declared as <string, int> but the second value you are adding is another string (from sr.ReadLine) I think you want a dictionary of <string, string>

Categories : C#

How to design system around state of object to not duplicate mechanisms in code and back-end?
If this were a project I was working on, I would not be looking to create a View to calculate this data. I would be looking at my application business logic. Whilst a fully normalised database makes perfect sense to the DBAs, there are cases where application performance and scalability can benefit greatly from a little de-normalization. If you have a reliable framework of business logic (i.e.

Categories : C#

C# getting first digit of int in custom class
Why not ToString the number and use Substring to get the first character? var number = 550; var result = number.ToString().Substring(0, 1); If for some reason you dont want to use string manipulation you could do this mathematically like this var number = 550; var result = Math.Floor(number / Math.Pow(10, Math.Floor(Math.Log10(number))));

Categories : C#

Thread safe disposal of WCF service
Or any other suggestions? Just follow the rule "one thread - one client". There's no reason to share database connections, http clients, service clients and so on between threads. As a rule, all of these objects has a tiny state, and any efforts to minimize resource usage via sharing them is a headache, since you need to synchronize cross-thread access to prevent objects' state from corrupti

Categories : C#

How to make asynchronous methods that use a queue thread safe
To simply add thread-safety you should use a ConcurrentQueue. It's a thread-safe implementation of a queue and you can use it just the same way you would use a queue without worrying about concurrency. However if you want a queue you can await asynchronously (which means that you're not busy-waiting or blocking a thread while waiting) you should use TPL Dataflow's BufferBlock which is very simila

Categories : C#

How to serialize a class containing queues for XML?
It depends on what serialization you are using. Using ISerializable it works just fine. [Serializable] class Program : ISerializable { public Program() { } public Queue<int> Queue = new Queue<int>(); private unsafe static void Main(string[] args) { var pr = new Program(); pr.Queue.Enqueue(1034); using (var stream = File.Create("path.txt"))

Categories : C#

How to check if datagridview input type matches with the underlying data type in c#?
I have analyze your source code. Everything works fine for me. Maybe there is error in your DataSource? public partial class Form1 : Form { private BindingList<Class> DataSource = new BindingList<Class>(); public Form1() { InitializeComponent(); dgvLoadTable.DataSource = DataSource; } private void dgvLoadTable_CellValidatin

Categories : C#

using {...} with new to instantiate anonymous type in C#
http://msdn.microsoft.com/en-GB/library/bb397696.aspx is the MS documenation, to quote: You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers (C# Programming Guide). The following example shows an anonymous type that is initialized with two properties named Amount

Categories : C#

Create a list of classes
List<MyArg> perfTestsArgs = new List<MyArg>() // <- close the bracket here, or remove () as @Mihai said { new MyArg("columns","1"), new MyArg("rows","1"), new MyArg("batch","1"), new MyArg("trips","400"), new MyArg("strict","true"), new MyArg("valueLength","1"), }; more details on initia

Categories : C#

How to Embedd notepad++ in my windows form?
What you want to do can be achieved differently. Embedding Notepad++ is a wrong idea. It is an independent executable that is not intended to be the "plugin of something"... but is is a great plugin holder itself. Check the Notepad++ documentation to create your own plugin, which will probably be easier and more reliable. If you want to stick with C#, use a dedicated Control to highlight some s

Categories : C#

RadioButton customization
All you need to do is change two Ellipses for Images and remove unused animations. <Style TargetType="RadioButton"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="RadioButton"> <Grid Background="Transparent"> <VisualStateManager.VisualStateGroups>

Categories : C#

Read mp3 Popularimeter in ID3.NET?
If it is not possible with ID3.NET you can try to use Taglib Sharp and find an example for POPM here: Check music file rating with VB.NET + WinForms

Categories : C#

Enable/Disable a control using Dependency Property in windows Phone
In your control binding for the button, you aren't actually binding to a value. The value converter code doesn't run because there is nothing prompting it to run. Instead, you would need to bind to a property value, and have that value change when a character is typed in either box, for example. Also, looking at your dependency properties, there is no place where you are actually calling the sett

Categories : C#

Change Redirect Url in Google Drive - C# (Part 2)
AuthorizationCodeMvcApp Takes two parameters in its constructor, so that's why you get the first error. You can't set controller and flowdata because they are read only, in the AuthorizationCodeMvcApp they are set only in the constructor! I think that the best solution for you is to just copy the content of AuthorizationCodeMvcApp and change line 46 to the right URI you want it to have.

Categories : C#


Recently Add
Process MainWindowTitle not displaying for all running processes
SendGrid Tutorial resulting in Bad Request
Dropdown list from table in ASP NET MVC
Newtonsoft.JSON Serialization Array, Object, or Null
Using LINQ to select a byte array
How to stop scripting?
C# access to object property after json decode
How to kill instance of Word/Excel File in C#
Datatypes for MemoryStream.Capacity vs MemoryStream.Length
How to remove a selected row from a table when using KnockoutJS
SqlCommand returns null even tho there is data in the database
Replacing words in a body of text from array
C# dropping milliseconds from Java SOAP call
C# Deserialize list in JSON
Deserialize xml by linq, default with many elements
How to Access Grid View from hub section Data Template Windows phone 8.1 in C#
Input dialogue popup on mouse click
WPF: Binding to MainWindow Property SOLVED
Why is setting a field many times slower than getting a field?
Change multiple materials in one GameObject in Unity3D
.NET MVC error client side with custom validation attribute
Windows Search Service - text saved in ansi (codepage 1251) format - search for non-english symbols gives no result
String.Split - Omit empty array elements OR below a certain length
RequiredFieldValidator does not validate when ValidationGroup applied
Which WCF's extension point should be used for setting context for each operation?
Determine var type depending on ternary (?) Operator on int array
Resolving Windows phone 8.1 Compilation Error: GetENumerator
Specific Ordering of a List of Objects using LINQ
'string' does not contain a definition for 'Fill' and no extension method 'Fill' accepting a first argument of type 'string' could be found
how can ı pass data from serverside to clientside
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.