Menu
  • HOME
  • TAGS

With NAudio howto capture an signal played

.net,audio,naudio

With NAudio, you can use WasapiLoopbackCapture to capture the soundcard output. Unfortunately, there is no way to specifically capture the audio from another application though.

Is there a difference between new List() and new List(0)

c#,.net,list,memory-management

Here is the actual source code (Some parts trimmed for brevity) static readonly T[] _emptyArray = new T[0]; public List() { _items = _emptyArray; } public List(int capacity) { if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); if (capacity == 0) _items = _emptyArray; else _items = new T[capacity]; } As...

inconsistent timing from .net StopWatch

c#,.net,timing,stopwatch,cudafy.net

As the TotalMilliseconds is constantly incrementing & you are trying to find differences between points in time, you need to subtract the sum of the preceding differences after the second one, hence : tIQR = watch.Elapsed.TotalMillisconds - (tHistogram + tHistogramSum); & tThresholdOnly= watch.Elapsed.TotalMillisconds - (tHistogram + tHistogramSum + tIQR); ...

OWIN use SignalR and prevent 'HTTP Error 403.14 - Forbidden'

asp.net,.net,owin,katana

You can write your own Middleware (thats the beauty of OWIN) to handle these requests. Ive made an example where it will return statuscode 200 and return empty: public partial class Startup { public void Configuration(IAppBuilder app) { app.Use<OnlySignalRMiddleware>(); app.MapSignalR(); } } public class OnlySignalRMiddleware : OwinMiddleware { public OnlySignalRMiddleware(OwinMiddleware...

External Datepicker not working

javascript,jquery,.net

Apparently your Array has no map method, which is part of ECMA-262 edition 5 and which your JS engine seems not to support? You can implement Array.prototype.map manually by taking it from somewhere like https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map.

Custom drawing using System.Windows.Forms.BorderStyle?

c#,.net,vb.net,winforms,custom-controls

If you want to get results that reliably look like the BorderStyles on the machine you should make use of the methods of the ControlPaint object. For testing let's do it ouside of a Paint event: Panel somePanel = panel1; using (Graphics G = somePanel.CreateGraphics()) { G.FillRectangle(SystemBrushes.Window, new Rectangle(11, 11,...

How to iterate over @Model.ICollection in Java Script function?

javascript,.net,asp.net-mvc,razor,icollection

This should do it using JsonConvert from newtonsoft.json <script> var coordinatesJson='@Html.Raw(JsonConvert.Serialize(Model.LoginCoordinates.ToArray())' var coordinates=JSON.parse(coordinatesJson); //you now have coordinates as javascript object var map; function InitializeMap() { // could loop over if needed for(var coords in coordinates) { // do something with coords } </script> ...

How can I handle exceptions in Web API 1.0 at my BaseAPIController

.net,asp.net-web-api

you probably should use an exception filter. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)] public sealed class ExceptionHandlerAttribute : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { base.OnActionExecuted(actionExecutedContext); var e = actionExecutedContext.Exception; if (e != null) { // do whatever you need with your exception } } You...

Capturing group recursively inside non-capturing group?

.net,regex

The .net regex implementation gives the possibility to store the substrings of a repeated capture group. So with this pattern that describes the whole string: \A(?:(\d+(?:-\d+)?)(?:,|\z))+\z (where \A and \z stand for the start and the end of the string) you obtain all the values in capture group 1 with...

How to compose two lambdas of type “delegate” in c#

c#,.net,generics,lambda

Does this what you want?: Func<int, int> a = p0 => p0 << 1; Func<int, int, int> b = (p0, p1) => p0 + p1; Delegate da = a; Delegate db = b; var inner = da.Method.GetParameters().Length < db.Method.GetParameters().Length ? da : db; var outer = inner == da ?...

MySQL database to combo box using mysqldatareader in c#.net [closed]

c#,mysql,sql,.net

Wow... Suppost your combox name is cbProducts, and you want fill it with the colum "description" of the query MySQL database to combo box using mysqldatareader in c#.net MySqlCommand cmd = new MySqlCommand("select * from product", connection); MySqlDataReader dread = cmd.ExecuteReader(); while (dread.Read()) { cbProducts.Items.Add(dread("description"); } ...

System.DBNull Error on formatting DataGridView C#

c#,.net,datagridview

DBNull.Value is of type DBNull and cannot be cast to a string. Instead, use Convert.ToString to handle this case. Demo Also, for what it's worth, DBNull.Value is not the same as null. See this answer for details....

Why when trying to upload a video file to youtube i'm getting InvalidCredentialsException?

c#,.net,youtube,youtube-api,google-client-login

ClientLogin (login and password) was deprecated as of April 20, 2012 and turned off on May 26 2015. This code will not longer work you need to switch to using Oauth2. I would like to also recomed you use the new Google client library Install-Package Google.Apis.YouTube.v3 ...

Foreign key not updating in entity frame work

c#,.net,entity-framework,foreign-keys

Base on Entity Framework does not update Foreign Key object I created public string ModifiedBy { get; set; } [DataMember] [ForeignKey("ModifiedBy")] public User ModifiedUser { get; set; } That means I additionally introduced a primitive type(string ModifiedBy ) for Modified User and specified ForeignKey. That resolved my issue...

ASP.NET MVC posting list from view to controller

c#,.net,asp.net-mvc,razor

That's probably a good candidate for an EditorTemplate to be honest, that way you don't have any issues with prefixing: @Html.EditorFor(m => m.TechnologyFilters) Without using an editor template though, a technique you can use is to specify the prefix in your partial declaration within the ViewDataDictionary, by doing: Html.RenderPartial("_TechnologyFilters", Model.TechnologyFilters,...

WPF Navigation using MVVM

c#,.net,wpf,mvvm

The AncestorType should be MainWindow not MainViewModel. MainViewModel is not a class that is part of the visual tree.

how can I add a column to IQueryable object and modify its values

c#,.net,linq,grid,devexpress

Simple example for using a non-anonymous class. public class MyLovelyClass { public Int32 Number { get; set; } public bool Selection { get; set; } } var packs = from r in new XPQuery<Roll>(session) select new MyLovelyClass() { Number = r.number }; gcPack.DataSource = packs; ...

Reading a text file with Tabs

c#,asp.net,.net,file,readfile

There's no tab entity defined in ISO-8859-1 HTML, so I think you can replace tab characters with some &nbsp; characters: if (File.Exists(path)) { using (TextReader tr = new StreamReader(path)) { while (tr.Peek() != -1) { var htmlLine = tr.ReadLine().Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;") + "<br/>"; Response.Write(htmlLine); } } } ...

Improve DataGridView rows managing

.net,vb.net,winforms,datagridview,datatable

what can I do to manage a DataSource instead of directlly manage the rows collection of the control A Class and a collection are pretty easy to implement as a DataSource and will also it will be pretty easy to modify your MoveUp/Dn methods for it. Class DGVItem Public Property...

The type or namespace name 'Json' does not exist in the namespace 'System' (are you missing an assembly reference?)

.net,json,jsonobject

That package is discontinued and shouldn't be used any more. If you have a console application, I could recommend two options: JSON.NET. Not a part of the .NET Framework itself, but much faster than Microsofts implementation; Microsofts implementation of the JavaScriptSerializer. Both are capable of reading and writing JSON. I...

Get an Element in a deep stack of Html Elements

c#,html,asp.net,.net

Since your input has an ID of Button1, use GetElementById. Failing that though, you'd have to query webBrowser.Document.All, which is a collection of all the elements in the HTML document. HtmlElement input = webBrowser1.Document.GetElementById("Button1"); ...

How to use HttpClient to Post with Authentication

c#,.net,httpclient

First you have to set the Authorization-Header with your <clientid> and <clientsecret>. Instead of using StringContent you should use FormUrlEncodedContent as shown below: var client = new HttpClient(); client.BaseAddress = new Uri("http://myserver"); var request = new HttpRequestMessage(HttpMethod.Post, "/path"); var byteArray = new UTF8Encoding().GetBytes("<clientid>:<clientsecret>"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); var formData...

SpecFlow Ambiguity in bindings

c#,.net,bdd,specflow

As @perfectionist has pointed out your problem is with your regexes. One is consuming all of the chars for both. Try this instead: Feature: ConversionUnencrypted Pdf-Pdf @mytag Scenario Outline: ConversionUnencrypted Pdf-Pdf Given I get Inputs Folder and list of Files '<inputFolder>' then '<getInputTokens>' Given I get '<outputDirectory>' ... and the...

Unconstrained type parameters casting

c#,.net,types,casting

The compiler sees the T2 and T identifiers and helpfully informs you that those types seem unrelated. That's absolutely correct, as they have no relation: there are no generic constraints that would assert any relations between them (I'm not saying that would be useful here though :) ). Whether this...

Unhandled exceptions and background workers

.net,exception-handling,backgroundworker

The other threads will carry on. Only the thread used by the BackgroundWorker will crash. An unhandled exception will be thrown. Since there is no exception handling in the event handler, it will get caught by the CLR as a last resort. This will not influence other threads....

QUERY IN C# ,where statement

c#,.net,select

I Assumed that you are using SQL this a generic query for your question: SQLCommand cmd = new SQLCommand(); cmd = "SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME= '" + combobox1.Text + "'"; here is what I recommend SQLCommand cmd = new SQLCommand(); cmd = "SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME=...

Formatting large numbers in C#

c#,.net,unity3d,formatting

I am using this method in my project, you can use too. Maybe there is better way, I dont know. public void KMBMaker( Text txt, double num ) { if( num < 1000 ) { double numStr = num; txt.text = numStr.ToString() + ""; } else if( num < 1000000...

Visual Studio Assembly force-installs Target Framework

c#,.net,visual-studio-2013,.net-framework-version

The targeted .NET version is the only version that the app will depend upon by default. Visual Studio will not automatically add higher and backwards compatible releases. Do this manually by adding other .NET versions to a configuration file: On the Visual Studio menu bar: Choose Project; Add New Item;...

How does convert.ToString(C0) behave?

c#,.net

You can brute force search the string for any currency symbols and change them to whatever character you want eg: string s = "$"; foreach (var c in s) { var category = CharUnicodeInfo.GetUnicodeCategory(c); if (category == UnicodeCategory.CurrencySymbol) { //Force convert the char to what every character you want }...

Notify winforms application by Sql Server database changes

c#,.net,sql-server,winforms,sqldependency

There's quite a few limitations with SqlDependency. To quote one relevant issue: The projected columns in the SELECT statement must be explicitly stated, and table names must be qualified with two-part names.Notice that this means that all tables referenced in the statement must be in the same database. (see https://msdn.microsoft.com/library/ms181122.aspx...

Why are nUnit tests just getting ignored when using TestCaseSource?

c#,.net,unit-testing,nunit

It's likely that your issue is being caused by your test runner not supporting the TestCaseSource attribute, particularly if it is being reported as Create. NUnit renames tests that use TestCaseSource, to combine the argument names into the name of the test. For your test, it should be reported as...

How to select rows from a DataTable where a Column value is within a List?

asp.net,.net,vb.net,linq,datatable

In the past, I've done this sort of like this: Dim item = From r as DataRow in dtCodes.Rows Where lstCodes.contains(r.Item("Codes")) Select r Does that work?...

XElement.Value is stripping XML tags from content

c#,.net,xml,xml-parsing,xelement

As others have said, this format is truly horrible, and will break as soon as the XML embedded in the JSON will contain double quotes (because in the JSON they will be encoded as \", which will make the XML invalid). The JSON should really be embedded as CDATA. Now,...

Check whether print command success or not

c#,.net,winforms,printing

This code doesn't actually print something, it's using the Shell to send a Print command to whichever program the user has installed to handle pdfs. This may or may not be Adobe Acrobat. The process will finish as soon as the verb is sent. It won't even wait until the...

How can i get list of my youtube videos from youtube?

c#,.net,winforms,youtube,youtube-api

You're trying to call a v2 URL (the one that starts with https://gdata), which no longer exists. Additionally, the location you got a developer key from is also deprecated; you won't use a "developer key," but the API key you get from console.developers.google.com -- NOT the client ID, though. You...

How to set public bool value in C# code behind, read in .ascx User Control?

c#,.net

You could cast the Page property to the right type, the page property needs a getter. (somewhere in your ascx codebehind): MyPageType page = this.Page as MyPageType; if(page != null) { bool templateBGOption = page.TemplateBGOption; } But in this way you are hard-wiring the page with the UserControl. Instead the...

.NET use IIF to assign value to different variables

.net,vb.net,conditional,variable-assignment,iif

What you're asking to do would have been possible in a language that supports pointer types (such as C/C++, or C# in unsafe mode) with dereferencing; VB.NET doesn't do that. The best you got to leverage is local variables, reference types, and (perhaps) ByRef. If it's a Class, its instantiation...

Feature-specific compatibility of a .NET 4.5 application on a system with .NET 4.0

c#,.net,zipfile

The easiest way to do this is probably to load the required code dynamically. You could use reflection to look for the required assembly, class and members if .NET 4.5 is detected. You could cache the results in delegates, to avoid reflecting every time. You could also use a plug-in...

OpenXml.WordProcessing.Justification always comes as OpenXmlUnknownElement

.net,ms-office,openxml,openxml-sdk

You need to read the documentation. TableCellProperties doesn't take the a Justification element. Link If you are trying to align elements within a cell, you need to put it into ParagraphProperties....

“CLR detected an Invalid Program” when compiling a constructor for List

c#,.net,linq,lambda,clr

The DeclaredConstructors property will return even the static constructor of List<>. You clearly can't invoke it. Use: ConstructorInfo foundConstructor = objectType.GetTypeInfo().GetConstructor(Type.EmptyTypes); ...

.NET web service gets null object

c#,.net,ajax,web-services,rest

Possibly the mistake in this line var data = '{ "c:":{"Id": "1", "Name": "myname"}'; should be var data = '{ "c":{"Id": "1", "Name": "myname"}'; ...

How to remove text from textbox/label without flicker

c#,.net,vb.net

I would advise to use another control rather than a TextBox. The way it repaints is just bad. You might have some luck when enabling double buffering on the control (something like here: How to prevent a Windows Forms TextBox from flickering on resize?), but I usually use a ListView...

Continuous deployment and running with TeamCiy

.net,continuous-integration,teamcity,exe,continuous-deployment

In order to achieve what you want to, you could try using a PowerShell build step and use the following script. Start-Process myprogram.exe This will return an object to you, but won't block the thread and won't cause your agents to wait for the process to end. Further documentation can...

Directory.Exists and FileSystemWatcher

c#,.net,filesystemwatcher

You simply see the Honest Truth, the directory is not actually deleted. The operating system actively prevents the directory from disappearing when a process has a handle opened on it. Like FSW does when you start watching. Or when the directory is the Environment.CurrentDirectory of a process. This doesn't otherwise...

How does System.Data.SQLite deal with .NET Data Types?

.net,sqlite,system.data.sqlite

I suggest you start with the driver-agnostic SQLite documentation on the subject. It explains the way booleans should be stored, and the different datetime serialization schemes, for example. For more details, System.Data.SQLite is open source, and while a bit crufty around certain edges, is generally quite easy to read. For...

How can I determine if an object of anonymous type is empty?

c#,.net

Anonymous types do not provide operator overloads for ==, although it wouldn't matter in this case since one of the arguments is typed object. However the C# compiler does provide Equals, GetHashCode, and ToString implementations. Use the static object.Equals, method which will do the appropriate null checks and then call...

Does MongoDB successful insert guarantee populated ID's?

c#,.net,mongodb-csharp,mongodb-csharp-2.0

Yes. If the operation completed without errors you are guaranteed that the documents have an ID (either created by you before the operation or by the driver in the operation itself). Moreover, since the IDs are generated by the driver itself (client-side) before calling the MongoDB server there's a good...

Microsoft Band and WPF

.net,wpf,dll,microsoft-band,.net-core

The current Band SDK does not support Windows desktop (i.e. Win32) applications. It supports only Windows Store and Windows Phone (i.e. WinRT) applications. Portable libraries can be confusing as the terms '.NETCore' and 'netcore451' refer to the Windows Store version of the .NET framework....

Web API - Set each thread with the HttpRequestMessage id?

c#,.net,multithreading,task-parallel-library,web-api

For context related problems, you can use CallContext.LogicalSetData and CallContext.LogicalGetData, which is merely an IDictionary<string, object> which flows between contexts, and has a copy-on-write (shallow copy) semantics. Since your data is immutable (according to the docs), you can map your correlation id to your threads managed thread id: protected async...

Exclusive lock using key in .NET

c#,.net,multithreading,locking

Put lock objects into dictionary indexed by the key - Dictionary<string, object> and grab objects by key to lock. If you need to dynamically add new key/lock object pairs make sure to lock around the dictionary access, otherwise if after construction you only read values from dictionary no additional locking...

Catch concurrency exception in EF6 to change message to be more user friendly

c#,asp.net,.net,entity-framework,entity-framework-6

You are executing an asynchronous method. This means that any exceptions will be thrown when you call await on the returned task or when you try to retrieve the results using await myTask; You never do so, which means that the exception is thrown and caught higher up your call...

Hashing speed - cryptic results (Hashing twice much slower than hashing once)

c#,.net,hash

Your results are most likely caused by disk caching. Assuming both tests operate on the same data, only the first read will result in significant I/O time. IE: Iteration 1, Test 1 : 30 seconds (= 20s disk read, 10s work). Iteration 1, Test 2 : 30 seconds (= 0s...

How to handle error in asp.net Httphandler?

javascript,c#,asp.net,.net

I think you are doing it wrongly. You shouldn't return javascript from http handler. They are meant to be used to process data. The alert should be shown based on the result of the Httphandler execution. What you can do is put try catch blocks in your http handler, and...

Dependency injection with unity in a class library project

c#,.net,asp.net-mvc,dependency-injection,unity

If you must use a DI Container like Unity (instead of Pure DI), you should install it into your Composition Root, which is 'The site'. From there, you can reference the library projects and configure your container....

Consuming and exposing webservices in one project (.NET)

.net,web-services,rest,soap

If you are trying to enrich the data from one source and combine that with information from another source, I think this is a decent solution. I think it is better to have one single point to talk to (your REST service), than to have two in your application and...

How to send Ctrl+S through SendKeys.Send() method to save a file(save as dialog)

c#,.net,windows,sendkeys

I believe you need to use: SendKeys.SendWait("^(s)"); Instead of: SendKeys.SendWait("^%s?"); Have a look at https://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.send(v=vs.110).aspx for more information....

Trying to delete user from database by Username in .NET MVC

c#,sql,.net,asp.net-mvc

If you want to delete a user, you need to get that user not creating a new instance of the User object. This needs to change: var deleteUserObj = new User {UserName = usernameToDelete}; To something like: var deleteUserObj = UserContext.LoadItemByUsername(usernameToDelete); Where LoadItemByUsername is a method that checks the db...

Serialize/Deserialize class containing byte array property into XML

c#,.net,xml,serialization,.net-4.0

As you've noticed, there are lots of characters that may not be present in an XML document. These can be included in your data, however, using the proper escape sequence. The default settings of the XmlTextReader cause it to mishandle this -- I think it interprets the escape sequences prematurely,...

I want to upload video on youtube using client side login. without open web page permission

c#,.net,google-api,youtube-api,google-api-dotnet-client

Your code is doing is doing everything correctly. The YouTube API doesn't allow for pure server authentication (Service Account). The only option available to you to upload files will be to use Oauth2 and authenticate your code the first time. I just sugest you make one small change add filedatastore....

Dependency Injection for concrete .Net classes

c#,.net,dependency-injection,ninject

If TcpServer is sealed and implements no interfaces, but you still want to decouple a client from its particular implementation, you'll have to define an interface that the client can talk to, as well as an Adapter from TcpServer to the new interface. It can be tempting to extract an...

Explain what problems could have this function (if any)

.net,vb.net,winapi,pinvoke,getlasterror

From the documentation of GetLastError: The Return Value section of the documentation for each function that sets the last-error code notes the conditions under which the function sets the last-error code. Most functions that set the thread's last-error code set it when they fail. However, some functions also set the...

Move windows form from a picturebox in C#

c#,.net,winforms,picturebox

Refer this code: private bool draging = false; private Point pointClicked; private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (draging) { Point pointMoveTo; pointMoveTo = this.PointToScreen(new Point(e.X, e.Y)); pointMoveTo.Offset(-pointClicked.X, -pointClicked.Y); this.Location = pointMoveTo; } } private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { draging = true;...

Custom DataType for Umbraco containing MultiUrlPicker

c#,.net,umbraco,umbraco6

I made it work finally using the following code: var urlPicker = new MultiUrlPickerDataEditor {Settings = new MultiUrlPickerSettings{ Standalone = false }}; Posting it here, in case anyone else ever struggle with the same thing....

How does the Take() method work in LINQ

c#,.net,linq,entity-framework

See Return Or Skip Elements in a Sequence. Take(N) will add TOP N to your SQL and only retrieve N records. For example (using my own SQL Server 2014 with EF 6.1): This LINQ: var query = await dbContext.Lookup .Where(w => w.LookupCd == '1') .Take(10) .ToListAsync(); Generates this SQL: SELECT...

Where to store an mp4 file in my project?

.net,vb.net,visual-studio,mp4

Try going Project>"Project Name" Properties>Resources>Add Resource>Add Existing File This should add the file into your resources folder. You can then access any file by going My.Resources.Name_Of_Resource...

WebApi Put how to tell not specified properties from specified properties set to null?

c#,.net,json,asp.net-web-api

I ended up using dynamic proxy for the properties, so that I could mark the properties written by JsonMediaTypeFormatter as "dirty". I used slightly modified yappi (did not really have to modify it, just wanted to - mentioning this if the code below does not exactly match yappi samples/API). I'm...

Concordion NUnit throws NullReferenceException when discovering test

.net,concordion

Congratulation for your first Concordion.NET tests. Unfortunately, there is an issue with the NUnit Test Adapter (https://github.com/nunit/nunit-vs-adapter/issues/9) that prevents loading of NUnit addins such as the one used to run Concordion.NET tests. As described on the website of Concordion, there is a workaround to be able to run Concordion.NET tests...

Listing directories by content size using C# [closed]

c#,.net,windows,linq

A small example here: class DirectorySize { public string DirectoryName; public long DirectorySizes; } public class Program { static void Main(string[] args) { string[] cDirectories = Directory.GetDirectories("C:\\"); List<DirectorySize> listSizes = new List<DirectorySize>(); for (int i = 0; i < cDirectories.Length; i++) { long size = GetDirectorySize(cDirectories[i]); if(size != -1) {...

String Format: How to add any number of zeros before string

c#,.net

int num = 4; string a = num.ToString("D4"); Documentation...

How to get current memory page size in C#

c#,.net,memory-management

Try Environment.SystemPageSize: Gets the number of bytes in the operating system's memory page. Requires .NET >= 4.0 In the remarks it is even written that: In Windows, this value is the dwPageSize member in the SYSTEM_INFO structure. ...

Best approach to upgrade MVC3 web app to MVC5?

c#,.net,asp.net-mvc,asp.net-mvc-5

There's a handy documented guide by Rick Anderson which he wrote to upgrade from MVC4, the same applies to you with the exception of the fact that the "Old version" of DLLs he mentions will be different to the ones that you will have, but the outcome will still be...

DialogBox with value verifications

c#,.net,winforms

The problem is you're trying to enable or disable the button when checking individual textboxes and they're conflicting with each other, instead the logic needs to be at a higher level. Change your textbox validation function to return a bool, and use that in ValidateAll to determine whether or not...

Entity Framework Invalid Column (Column Does Not Exist in Database or Code)

c#,.net,entity-framework

This is not an Entity Framework problem. It's something in the database, which sadly, is the part you have not given us any details about, not even which RDBMS it is. It sounds like you have a SQL Server database that was migrated from some other RDBMS. I suspect that...

Automapper AfterMap function initialising classes

.net,vb.net,automapper

The objects have values in them because they are called after Mapping.Map function is called and that's where actual object with values is passed and then AfterMap function is called and that's how it has the values in it.

Regex to remove `.` from a sub-string enclosed in square brackets

c#,.net,regex,string,replace

To remove all the dots present inside the square brackets. Regex.Replace(str, @"\.(?=[^\[\]]*\])", ""); DEMO To remove dot or ?. Regex.Replace(str, @"[.?](?=[^\[\]]*\])", ""); ...

Set default value for string prompt

c#,.net,autocad,autocad-plugin

I paste you some code as example for the different prompts : using System; using System.Collections.Generic; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.Geometry; using Autodesk.AutoCAD.ApplicationServices; namespace EditorUtilities { /// <summary> /// Prompts with the active document ( MdiActiveDocument ) /// </summary> public class EditorHelper : IEditorHelper { private readonly Editor _editor; public EditorHelper(Document...

Post messages from async threads to main thread in F#

.net,powershell,f#,system.reactive,f#-async

I ended up creating an EventSink that has a queue of callbacks that are executed on the main PowerShell thread via Drain(). I put the main computation on another thread. The pull request has the full code and more details. ...

Is Serialization the same as GetBytes?

.net

No, GetBytes() just converts a string to its binary represenation using the asked encoding. So it does serialize, but it is very specific to strings. When you want to serialize any object to bytes, you could use the BinaryFormatter. More about how to serialize an object using the BinaryFormatter can...

Programmatically accessing TFS history [closed]

c#,.net,powershell,tfs

Shai Raiten's Blog is great for learning the TFS API. For getting file history - read this post: http://blogs.microsoft.co.il/shair/2014/09/10/tfs-api-part-55-source-control-get-history/...

Related entity not loaded

c#,.net,entity-framework

Mark your relation property with virtual keyword for EF's proxy to be able to overload it: [ForeignKey("SchoolClassId")] public virtual SchoolClass SchoolClass { get; set; } Also, be sure that context's DbContext.Configuration.ProxyCreationEnabled property value is set to true (by default it is). These two conditions enabling lazy loading of your relations....

Filtering a sequence of options and collecting the values of all the Somes. Is there a built-in function in F# for that?

.net,f#

The easiest way is to use Seq.choose s |> Seq.choose id Here we use id as the input is the same as the output...

DateTime.Parse ignoring my IFormatProvider?

c#,.net,parsing,datetime

If you follow through the reference source you'll see that DateTimeFormatInfo is extracted from your CultureInfo by simply referencing CultureInfo.DateTimeFormat. There is a Calendar property on DateTimeFormatInfo, which is what is used in parsing. These two are normally the same (i.e. reference equal), the fact you Clone your CultureInfo results...

String.Equals vs Sting.Compare vs “==” in Action. Explanation needed

c#,.net,string,string-comparison

Why does the first comparison (string.compare) work and the other two comparison methods does not work in THIS PARTICULAR CASE There are invisible characters (particularly, a Left-to-Right mark (Thanks @MatthewWatson)) in your code. You can view them with any hex editor: This is over-looked by string.Compare, while it isn't...

Does .NET Framework 4.5 work on Windows Server 2003?

.net,windows-server-2003

No. .NET 4 is the last framework version supported on Windows Server 2013. .NET 4.5 and higher are not supported on Windows Server 2013. See .NET Framework Versions and Dependencies....

How do I prevent MySQL Database Injection Attacks using vb.net?

mysql,.net,database,vb.net,sql-injection

MySQLCon.Open() Dim SQLADD As String = "INSERT INTO members(member,gamertag,role) VALUES(@memberToAdd, @memberGamingTag, @memberRole)" COMMAND = New MySqlCommand(SQLADD, MySQLCon) COMMAND.Parameters.AddWithValue("@memberToAdd", memberToAdd.Text) COMMAND.Parameters.AddWithValue("@memberGamingTag", membersGamertag.Text) COMMAND.Parameters.AddWithValue("@memberRole", membersRole.Text) COMMAND.ExecuteNonQuery() memberToAdd.Text = "" membersGamertag.Text = "" membersRole.Text = "" MySQLCon.Close() MySQLCon.Dispose() You don't need to use...

Application is missing required files

c#,.net,windows,winforms,sharpdevelop

Your program is looking for compas.ico inside the build directory, while it probably resides in some other directory in your project.

Creating an Expression that returns an object

c#,.net,lambda,expression

You can create an Expression<Func<E>> and then use a lambda expression to return your entity once the expression is invoked. public void Persist<E>(E entity) { Expression<Func<E>> expr = () => entity; PersistRequest request = TranslateExpression<PersistRequest>(expr); } public R TranslateExpression<R>(Expression exp) where R : DbRequest { } However, your TranslateExpression method...

How to set default length on all fields in entity framework fluent api?

c#,.net,entity-framework,ef-fluent-api

You can use something called Custom Code First Conventions, but only if you're using Entity Framework 6+. As @ranquild mentions, you can use modelBuilder.Properties<string>().Configure(p => p.HasMaxLength(256)); to configure the default maximum length for all string properties. You can even filter which properties to apply your configuration to: modelBuilder.Properties<string>() .Where(p =>...

How to add assemblies to WiX toolset setup, which comes from a nuget package?

c#,.net,wix

We add each of them as a separate component with its own GUID : <Component Id="Xceed.Wpf.AvalonDock.dll" Guid="{3E99B3EA-8528-4125-A8BA-B492B341479C}"> <File Id="Xceed.Wpf.AvalonDock.dll" Name="Xceed.Wpf.AvalonDock.dll" Source="$(var.project.TargetDir)Xceed.Wpf.AvalonDock.dll" KeyPath="yes" DiskId="1" /> </Component> ...... <Component Id="Xceed.Wpf.Toolkit.dll" Guid="{A9809E88-A097-4FFF-B311-8CB49B1B2FC5}"> <File Id="Xceed.Wpf.Toolkit.dll" Name="Xceed.Wpf.Toolkit.dll"...

Get the method name that was passed through a lambda expression?

.net,vb.net,reflection,delegates,pinvoke

I would not do this. It would be simpler to pass a string var representing the error message you want to display or a portion thereof (like the function name). The "simplest" way would be to use an Expression Tree. For this, you would need to change the signature of...

Why when adding items to combobox it's adding the same item many times?

c#,.net,winforms

Create a new instance of ComboboxItem each time you want to add a new item to the combo box: for (int i = 0; i < result.Items.Count; i++) { ComboboxItem item = new ComboboxItem(); item.Text = result.Items[i].Snippet.Title; item.Value = result.Items[i].Id; comboBox1.Items.Add(item); } ...

Replace string :"{ using regex

.net,regex,replace

I'm pretty sure that you don't need a regular expression for this. Just use var str2 = str.Replace(":\"{", ":{").Replace("}\"", "}"); ...

Empty readonly Action delegate

c#,.net

This change is technically observable: there is always the possibility that some code indirectly compares two new Action(() => {}) instances for equality, and where they would previously not compare equal, they do now. For an example, if you expose an public event Action X;, you might make sure to...

Elasticsearch and C# - query to find exact matches over strings

c#,.net,database,elasticsearch,nest

You can use filtered query with term filter: { "filtered": { "query": { "match_all": { } }, "filter": { "bool" : { "must" : [ {"term" : { "macaddress" : "your_mac" } }, {"term" : { "another_field" : 123 } } ] } } } } NEST version (replace dynamic...