FAQ Database Discussion Community


Constructor Injection vs IocFactory

c#,.net,dependency-injection,inversion-of-control
Today at work a collegue and I had a discussion about the following: Basically we have a rule engine which works in the following way: RuleExecutor Gets all rules to execute in the constructor like public RuleExecutor(ICollection<IRule> rulesToExecute) { ... } Executes all rules by calling rule.ApplyRule(); for each rulesToExecute...

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

c#,.net,regex,string,replace
I have this regex in C#: \[.+?\] This regex extracts the sub-strings enclosed between square brackets. But before doing that I want to remove . inside these sub-strings. For example, the string hello,[how are yo.u?]There are [300.2] billion stars in [Milkyw.?ay]. should become hello,[how are you?]There are [3002] billion stars...

XElement.Value is stripping XML tags from content

c#,.net,xml,xml-parsing,xelement
I have the following XML: <Message> <Identification>c387e36a-0d79-405a-745c-7fc3e1aa8160</Identification> <SerializedContent> {"Identification":"81d090ca-b913-4f15-854d-059055cc49ff","LogType":0,"LogContent":"{\"EntitiesChanges\":\" <audit> <username>acfc</username> <date>2015-06-04T15:15:34.7979485-03:00</date> <entities> <entity> <properties> <property> <name>DepId</name> <current>2</current> </property>...

Empty readonly Action delegate

c#,.net
There are a number of places in our code where () => {} is used (required Action parameter in methods of third-party library). To make code cleaner I created the following class: public static class Empty { public static readonly Action Action = () => {}; } Now it is...

Is Serialization the same as GetBytes?

.net
Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes. Found this on google. I use .Net to send packets using a socket connection. I use Encoding.Default.GetBytes(). Serialization is confusing, what is the difference of it to GetBytes?...

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

c#,.net,generics,lambda
Lets assume we have defined two Lambdas. Func<TInput, TOutput> a = …; Func<TInput1, TInput2, TOutput> b = …; Now lets assume that we have some code that does not work with generics and receives these Lambdas as not further typed delegates. delegate da = a; delegate db = b; In...

Creating an Expression that returns an object

c#,.net,lambda,expression
I have this method: public R TranslateExpression<R>(Expression exp) where R : DbRequest { //... } In another class I have the following method: public void Persist(E entity) { Expression expr = Expression.Return(entity); //Does not compile, but I'm looking for something like this PersistRequest request = TranslateExpression<PersistRequest>(expr); } How can I...

Improve DataGridView rows managing

.net,vb.net,winforms,datagridview,datatable
SCENARIO I'm manually filling a DataGridView with a DataGridViewRow collection: I created the columns at design time in the GUI builder of Visual Studio. First column takes an Integer value, its a DataGridViewTextBoxColumn. Second column takes an Icon object, its a DataGridViewImageColumn. Third column takes a String value, its...

Get an Element in a deep stack of Html Elements

c#,html,asp.net,.net
I'm navigating to a website using WebBrowser object in C# and i want to get a Html Element that exist in that website but that element is in a deep ugly stack of other elements in fact the address is : html -> frameset -> frame#mainFrame -> html -> body...

System.DBNull Error on formatting DataGridView C#

c#,.net,datagridview
I'm new to C# so I have been following some guides and adapting it to fit my application. Here is one of the ones I followed from Microsoft. I have used the same code as what they have suggested and I get an error. My code simply looks at the...

Recycling app pool each time something is published

.net,iis,lucene,umbraco,application-pool
I'm working on an Umbraco site where I have custom sections, and therefore use the application.config and trees.config files. I have a problem where every time I publish something, the app pool recycles with the following message: w3wp.exe Information: 0 : _shutDownMessage=CONFIG change HostingEnvironment initiated shutdown CONFIG change HostingEnvironment caused...

Why are nUnit tests just getting ignored when using TestCaseSource?

c#,.net,unit-testing,nunit
I am having a lot of difficulty getting the nUnit TestCaseSource attribute to work correctly in nUnit 2.6.4.14350. When running the unit tests through VS2010, it just says the tests are being ignored, without any additional information as to why. The Create test just appears greyed out on the test...

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

c#,asp.net,.net,entity-framework,entity-framework-6
I am using EF6.1 and i would like to change the message to a more system specific message when the below exception is thrown. Store update, insert, or delete statement affected an unexpected number of rows (0) Now, my problem is i cannot seem to catch the exception? I have...

Application is missing required files

c#,.net,windows,winforms,sharpdevelop
Pic of Error: http://s23.postimg.org/7uj6qcxtn/9708083373e57a9ec91e4296e302f88e.png Cannot Download the Application. The Application is missing required Files. Contact Application Vendor For Assistance. So I'm building a windows form application using SharpDevelop 5.2 and I'm trying to make a standalone/version someone else would be able to use on another machine. In sharpdevelop (and visual...

Listing directories by content size using C# [closed]

c#,.net,windows,linq
I'm trying to list all folders of my c drive excluding the document folder which i do not seem to have access to. This first seemed rather simple to me but i found myself still struggling with it despite the seemingly rich .net library. I can't post any code as...

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

.net,sqlite,system.data.sqlite
I'm struggling to find documentation around System.Data.SQLite's behaviour in regards to the various .NET data types. For example, how does System.Data.SQLite store .NET Booleans in an SQLite database? There are several possible methods: Integers 0 and 1 Integers 0 and –1 Text 'True' and 'False' Text 'T' and 'F' Text...

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

.net,vb.net,reflection,delegates,pinvoke
Is it possible to retrieve via Reflection the real method name that was passed through a lambda expression? I would like to platform invoke some functions with a better error-handling, then to avoid repeating tons of Marshal.GetLastWin32Error conditionals, I thinked in create a generic method to automate that, where I...

Automapper AfterMap function initialising classes

.net,vb.net,automapper
Can anyone please explain how does the AfterMap function initalises the class objects passed in the lambda expression? When i run this bit of code as myself, it populates the dest object with my details. i can't figure out how is it doing that? but if someone can tell me...

How does convert.ToString(C0) behave?

c#,.net
I have different scenarios. I need output where the value must return comma separated values in ₹ format which it does in my system where I have the ₹ rupee symbol. Whereas in the user system C0 returns $ value with comma separated values I do not know if he...

.NET web service gets null object

c#,.net,ajax,web-services,rest
I'm trying to save an object using ajax call and .NET REST web service but I get null object on .NET side. Please help me to find out what's the issue. C# Object: [DataContract] public class Customer { [DataMember] public int Id { get; set; } [DataMember] public string Name...

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

c#,.net,winforms
In the top of form1: public class ComboboxItem { public string Text { get; set; } public object Value { get; set; } public override string ToString() { return Text; } } List<string> results = new List<string>(); Then: ComboboxItem item = new ComboboxItem(); var result = videoCatagories.Execute(); for (int i...

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

c#,.net
I want to slightly modify a user control that is being loaded by various .aspx pages. If I set a bool value in the .aspx.cs page public bool showTemplateBGOption; public bool TemplateBGOption { set { showTemplateBGOption = false; } } How can I read the bool value showTemplateBGOption in the...

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

c#,.net,list,memory-management
Is there a difference between new List<T>() and new List<T>(0) ? May be this is a micro-optimization, but the idea is to understund the difference in term of memory allocation....

ASP.NET MVC posting list from view to controller

c#,.net,asp.net-mvc,razor
I have a view model in my ASP.NET MVC application: public class FiltersViewModel { public IEnumerable<SelectListItem> AvailableFilters { get; set; } // fills a drop down menu public IList<TechnologyFilter> TechnologyFilters { get; set; } public IList<ContractTypeFilter> ContractTypeFilters { get; set; } public FiltersViewModel() { this.TechnologyFilters = new List<TechnologyFilter>(); this.ContractTypeFilters =...

How to remove text from textbox/label without flicker

c#,.net,vb.net
I want to create a textbox/label to display input/output from a serial connection. This program will be running over long periods of time, and since I don't want massive memory usage, I'm periodically reducing the length of the textbox content when it reaches a maximum value. Unfortunately, I've found that...

How does the Take() method work in LINQ

c#,.net,linq,entity-framework
I have a question regarding LINQ's Take() Method. I have a somewhat large table I'm querying in my web app, and I only want to return say N number of rows from the table. I've read through the MSDN documentation, but I can't see where it states if Take() first...

DateTime.Parse ignoring my IFormatProvider?

c#,.net,parsing,datetime
It looks to me like .NET is ignoring the TwoDigitYearMax property of the CultureInfo (IFormatProvider) I pass for parsing? Specifically, I cannot explain why the last line of this says 1930, and not 2030. Can anyone reproduce or explain it? Windows 7, .NET 4.0, en-US system settings. using System; using...

Directory.Exists and FileSystemWatcher

c#,.net,filesystemwatcher
Why does Directory.Exists returns true for a directory observed by FileSystemWatcher even if it was deleted. I must call EnableRaisingEvents = false before checking Directory.Exists since it always returns true. Edit: I am trying to check if folder was deleted or connection lost using error event. To add a delay...

Post messages from async threads to main thread in F#

.net,powershell,f#,system.reactive,f#-async
There is a subscription to an observable that sends out log messages. Some of the log messages come from other threads because they are are in F# async blocks. I need to be able to write out the messages from the main thread. Here is the code that currently filters...

Dependency injection with unity in a class library project

c#,.net,asp.net-mvc,dependency-injection,unity
I am new with dependency injection pattern. That's why little confused about few things. Scenario: I have a class library project called 'MailCore'. This project has interface and classes that perform all email sending stuff. I have a mvc project 'The site'. It uses the 'MailCore' project to send email....

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

c#,.net,linq,lambda,clr
I'm running into a strange problem when compiling a lambda expression for a parameterless constructor into a delegate. It works for almost all types that I have tried. Only the List<> is producing a “CLR detected an Invalid Program”. A Collection<> or an inherited class from List<> would not present...

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

c#,.net,entity-framework,ef-fluent-api
Is it possible to set default length of all string fields (unless I say otherwise)? At the moment it really bugs me to go and add something like modelBuilder.Entity<Game>().Property(x => x.YardLine).HasMaxLength(256); to each and every string field, just to avoid having nvarchar(max) on all my strings columns in the database....

Custom DataType for Umbraco containing MultiUrlPicker

c#,.net,umbraco,umbraco6
I am trying to create a custom DataType for Umbraco containing group of elements which include a TextBox, MediaPicker and a MultiUrlPicker. I can create a Text Box using the following snippet: var textBox = new TextBox(); and a Media Picker using the following snippet: var mediaPicker = new SimpleMediaPicker();...

Does .NET Framework 4.5 work on Windows Server 2003?

.net,windows-server-2003
Can anyone tell me if Microsoft .NET Framework 4.5 is compatible with Windows Server 2003 or not?

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

c#,.net,hash
I'm trying to understand why hashing of multiple hashes is much slower than one hash. In the following test I hash a file twice - first with SHA1 and then with both SHA1 and SHA256. The first execution shows the expected results - disk read dominates the time used -...

Unhandled exceptions and background workers

.net,exception-handling,backgroundworker
In our application we use several background workers which are executed using SERVICENAME__bgw.RunWorkerAsync() where SERVICENAME is one of several different background worker processes executed by different timers. We recently saw this error message that was shown after an unhandled error bubbled up to the top of the call stack: My...

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#
A common pattern in F# is to want to filter something by whether it is "Some"thing and in case it is, getting its value: module Option = let values s = s |> Seq.filter Option.isSome |> Seq.map Option.get I have the idea I've seen something like that in the F#...

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

c#,.net,wix
I use the Votive-project type to create a setup with the WiX toolset. I know, that I can add an assembly like this to the setup: <File Id="FILE_myproject.dll" Source="$(var.myproject.TargetPath)" KeyPath="yes" /> What I don't know is, how can I add referenced assemblies to the setup, which comes in a nuget...

How to handle error in asp.net Httphandler?

javascript,c#,asp.net,.net
I have Httphandler in asp.net that return a file. In code I have Response.AddHeader("Content-Disposition", "attachment; filename=somefile.ext"); so the page URL remains unchanged. But in case of error in Httphandler URL become some thing like this http://localhost:55161/document.axd and I have white screen. How I can return, for example, javascript alert from...

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

c#,.net,winforms,youtube,youtube-api
I installed the google api 3 and the OAuth2. And i tried the google develope example: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Google.GData.Client; using Google.GData.Extensions; using Google.GData.YouTube; using Google.GData.Extensions.MediaRss; using Google.YouTube; namespace Youtube_Manager { public partial class...

Update all properties of object in MongoDb

c#,.net,mongodb,mongodb-csharp,mongodb-csharp-2.0
I'm using the MongoDB .Net driver in my project. I want to update all of the properties of my object that is stored in MongoDB. In the documentation, update is shown like this: var filter = Builders<BsonDocument>.Filter.Eq("i", 10); var update = Builders<BsonDocument>.Update.Set("i", 110); await collection.UpdateOneAsync(filter, update); But I don't want...

How to convert this JSON to a datatable?

c#,.net,json,asynchronous,json.net
[ [ "<div id=\"status\" style=\"width:20px; height:20px; \" class=\"circle red\"></div>", "<a runat=\"server\" id=\"link0\" href=\"MachineDetails.aspx?PageName=PCsByLocation.aspx&MachineName=AUBDW012\">AUBDW012</>", "Dye, Paul", "", "AsiaPacific / Australia / BrisbaneDistribution", "<div id=\"divonoffswitch\" class=\"onoffswitch\"><input type=\"checkbox\" name=\"onoffswitch\"...

External Datepicker not working

javascript,jquery,.net
I'm working with an external jss library that will let me use a datepicker that doesn't cut off the previous and next months dates. I'm getting an error when going through the coding. code $.fn.calendar = function (options) { var _this = this; var opts = $.extend({}, $.fn.calendar.defaults, options); var...

How to convince sql server 2008r2 to use clr v4.0 instead of v2.0?

.net,sql-server,sql-server-2008-r2,sqlclr
I have sql server 2008r2. According to my internet research it supports .net framework 4.0. I tried to install my assembly with sql clr functions and receved an error. CREATE ASSEMBLY for assembly 'MyAssembly' failed because the assembly is built for an unsupported version of the Common Language Runtime. Query...

How to get current memory page size in C#

c#,.net,memory-management
I need to determine the memory page size in C# without using "Kernel32.dll" SYSTEM_INFO si; GetSystemInfo(&si); This is very important because the code should be cross platform and we should not have platform specific code. Is there any .NET class who provides that data? Thanks, Valentin...

SpecFlow Ambiguity in bindings

c#,.net,bdd,specflow
I'm working with Spec-flow for quite some days. I am facing "Multiple matching found.Navigating to first match", while Debugging this can be solved, but when I'm running the entire solution Its failing because of Ambiguity in bindings. I'm running around 4 C sharp class files in a Single project Feature:...

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

c#,sql,.net,asp.net-mvc
I am new to C# MVC and am having trouble figuring out how to make the connection to the specific user I am trying to delete. I have a table that reads the users in by username (user.UserName) @using (Html.BeginForm("DeleteUser", "Manage", FormMethod.Post)) { <table class="table"> <tr> <th>Username</th> <th>Role</th> </tr> @foreach...

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

asp.net,.net,vb.net,linq,datatable
Say you had a table in SQL and you wanted to find all the rows where a particular column could be one of 3 options. You could write something like this: SELECT * FROM MyTable WHERE uid IN (123, 456, 789) That's effectively what I want to do with a...

How to use HttpClient to Post with Authentication

c#,.net,httpclient
I am trying to do the following curl (which works for me) in C# using HttpClient. curl -X POST http://www.somehosturl.com \ -u <client-id>:<client-secret> \ -d 'grant_type=password' \ -d 'username=<email>' \ -d 'password=<password>' \ -d 'scope=all The C# Code: HttpClientHandler handler = new HttpClientHandler { Credentials = new System.Net.NetworkCredential ("my_client_id", "my_client_secret")...

Foreign key not updating in entity frame work

c#,.net,entity-framework,foreign-keys
I have a class like public class Document { [Key] public int Id { get; set; } public User ModifiedBy { get; set; } public DateTime ModifiedDate { get; set; } } Here “User” is a class with some properties (all are primitive types ) Here is my mapping of...

Consuming and exposing webservices in one project (.NET)

.net,web-services,rest,soap
What is best practice concerning consuming and exposing webservices in one project? (.net) I need to create a rest webservice to expose data. The rest webservice would need to consume this data from another (SOAP) webservice from a third party. (The data needs to be merged with data present in...

QUERY IN C# ,where statement

c#,.net,select
How can I write this query on c# : SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME=combobox1.text; ...

Setting binding on usercontrol to mainwindow's ViewModel

.net,wpf,xaml,mvvm,data-binding
I have following user control <UserControl x:Class="Station.Controls.FilterTraceDataControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d"> <TextBox x:Name="PartNumbTextBox" Width="120" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="5,0,0,0" Height="25"/>...

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

c#,.net,database,elasticsearch,nest
I need a way to search documents using a plain exact match over two or multiple fields which are of type "string" and "integer". I'd like to avoid standard query as I don't care about scoring or best match, just a yes/no outcome if both the fields match or not....

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

c#,mysql,sql,.net
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()) { } using mysqldatareader not a mysqldataadapter....

Reading a text file with Tabs

c#,asp.net,.net,file,readfile
In a text file I use TAB to create a column-like grid, but apparently those tabs are just read as spaces, which of course breaks the formatting. This is my code (path is the file path, e.g. D:/folder/testtt.txt): if (File.Exists(path)) { using (TextReader tr = new StreamReader(path)) { while (tr.Peek()...

Related entity not loaded

c#,.net,entity-framework
I'm starting a new entity framework project and I'm defining relations among entities. I defined this simple entities: [Table("db_owner.Students")] public partial class User { [Key] public int Id { get; set; } [Required] [StringLength(50)] public string Name { get; set; } public int? SchoolClassId { get; set; } [ForeignKey("SchoolClassId")] public...

Capturing group recursively inside non-capturing group?

.net,regex
So I've got the following input: 1,6-10,10000,2,10-11 And the following regex: ^\d+(?:,(\d+|\d+-\d+))*$ in the .NET Regex I want to match each of the groups between the commas but I also want the capturing groups to end up like the following: Group 1: 1 Group 2: 6-10 Group 3: 10000 Group...

Where to store an mp4 file in my project?

.net,vb.net,visual-studio,mp4
I have been studying vb.net for a couple of months now and I want to try something new. I have this sample project to try. It is a web browser and I want that if a button will be clicked, a video will play immediately. This is what my application...

Unconstrained type parameters casting

c#,.net,types,casting
My situation: interface ISomeInterface { void DoSmth<T>(T other); } class Base : ISomeInterface { public virtual void DoSmth<T>(T other){ // for example do nothing } } class Derived<T2> : Base { Action<T2> MyAction {get;set;} public override void DoSmth<T>(T other){ if(typeof(T2).IsAssignableFrom(typeof(T))) MyAction((T2) other); } } This gives me an error: Cannot...

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

c#,.net,linq,grid,devexpress
var packs = from r in new XPQuery<Roll>(session) select new { Number = r.number Selection = new bool() }; gcPack.DataSource = packs; I want to add another column to my grid control with: Selection = new bool(). It will be added to the grid but I can't change its...

Programmatically accessing TFS history [closed]

c#,.net,powershell,tfs
I have a solution under TFS source control and had written some sample code using an external library that was deleted a few months ago. I am certain that the code was checked in before that class file was deleted. I am able to manually browse to previous versions of...

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

.net,json,jsonobject
I am using .NET Framework 4.5 and I'm having this issue. The type or namespace 'Json' does not exist in the namespace 'System' So, I tried to Install-Package System.Json -Version 4.0.20126.16343 but I had this issue afterwards. The type 'System.Uri' is defined in an assembly that is not referenced. You...

Dependency Injection for concrete .Net classes

c#,.net,dependency-injection,ninject
What is the preferred way for injecting/isolating classes that are sealed in dlls and do not implement interfaces? We use Ninject. Let's say that we have a class "Server" and we want to inject/isolate the class TcpServer which "Server" uses. Don't want to be too specific because I want to...

With NAudio howto capture an signal played

.net,audio,naudio
Is there any way to capture a sound signal being played (by another application) in .NET (with or without the NAudio library)? What I want to do is build an graphical visualization of the sounds played (like there are plenty apps), but without playing the sound itself (which seems non...

Serialize/Deserialize class containing byte array property into XML

c#,.net,xml,serialization,.net-4.0
My data class that will be serialized into XML look like this: [XmlType(TypeName = "SPCFileInfo")] [Serializable] public class SPCFileInfoProtocol { [XmlElement("CompanyCode")] public string CompanyCode { get; set; } [XmlElement("FileName")] public string FileName { get; set; } [XmlElement("FileVer")] public int FileVer { get; set; } [XmlElement("FileSize")] public long FileSize { get;...

Visual Studio Assembly force-installs Target Framework

c#,.net,visual-studio-2013,.net-framework-version
I have this Assembly targeted at .NET 3.5. The code will work on later versions as well, but I like this to work on Windows XP. I mean, .NET is backwards compatible, right? I can run apps for .NET 3.5 on Windows 8.1. However, when I run my own assembly,...

Set default value for string prompt

c#,.net,autocad,autocad-plugin
The editor class has a method called GetString which prompts the user for a string value via AutoCAD's command prompt. I call it in this wrapper method: public static string PromptUserForString(string message = "Enter a string: ", string defaultAnswer = "") { return _editor.GetString("\n" + message).StringResult; } The argument message...

Move windows form from a picturebox in C#

c#,.net,winforms,picturebox
I have a windows form without any border. So i added a picture box and i want the whole form to be moved when that picture box is clicked. public const int WM_NCLBUTTONDOWN = 0xA1; public const int HT_CAPTION = 0x2; [DllImportAttribute("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg,...

Microsoft Band and WPF

.net,wpf,dll,microsoft-band,.net-core
I have downloaded the sample code for Band SDK for Windows. Then I added a new WPF project and grabbed the latest SDK through Nuget (Version 1.3.10518.1). Now under packages\Microsoft.Band.1.3.10518\lib, the following folders are contained: netcore451 portable-net45+win+wpa81 portable-win81+wpa81 wpa81 Now as I need .NET 4.5 support I have referenced the...

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

.net,asp.net-web-api
I am currently using Web API 1.0 and .NET 4.0 I need a function that can take care of the noise of catching and handling exceptions in my Base API so that I dont need to write that in every RESTful operation. public int Get(WelcomeTeamNotes note) { try { return...

Explain what problems could have this function (if any)

.net,vb.net,winapi,pinvoke,getlasterror
SCENARIO When P/Invoking, I thinked it could be a great idea to simplify/reduct tons of code by designing a generic function that calls the function, then it checks for the GetLastWin32Error I'm using this code: ''' <summary> ''' Invokes the specified encapsulated function, trying to provide a higher safety level...

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

c#,.net
I'd like to have strings that have zeros before them. I use this code: string a = string.Format("{0:00}",7); The above code gives a two digits string, but what if I want a n digit string? Let's say n = 5, how can I use string.format to get something like 0004?...

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
When I upload video to YouTube using client side login. The first time redirect to UI for permissions. I want upload without redirect to web page. I need to execute this code on server. Here is my code. private async Task<string> Run(string title, string description, string filepath) { var videoID...

Exclusive lock using key in .NET

c#,.net,multithreading,locking
I have used the lock statement in C# to exclusively execute a piece of code. Is there a way to do same based on a key. for e.g.: lock(object, key) { //code-here } I have a method which has some piece of code that is not thread-safe, but only if...

WPF Navigation using MVVM

c#,.net,wpf,mvvm
I'm trying to follow the answer provided in this post, but I must be missing something trivial. I've defined my DataTemplates as App.xaml as follows: <Application.Resources> <DataTemplate DataType="{x:Type vm:BlowerViewModel}"> <v:BlowerView /> </DataTemplate> <DataTemplate DataType="{x:Type vm:HomeViewModel}"> <v:HomeView /> </DataTemplate> </Application.Resources> Then, in my MainWindow.xaml I've defined the following code: <Window x:Class="App.MainWindow"...

Best approach to upgrade MVC3 web app to MVC5?

c#,.net,asp.net-mvc,asp.net-mvc-5
I have a web application which runs on Azure which is currently running MVC3/C#, EF6.1, .NET4.5. I would like to upgrade it to MVC5 to be: a) Current b) Get benefit of new features c) Get Performance gains. This is a part of a performance project, so hopefully there will...

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

javascript,.net,asp.net-mvc,razor,icollection
I have a @Model.LoginCoordinates where LoginCoordinates is ICollection<Coordinates>. The Coordinates class: public class Coordinates { public int Id { get; set; } public double Latitude { get; set; } public double Longitude { get; set; } } Inside the view in I have: <script> function f(){ for (var i =...

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

c#,.net,entity-framework
So I have seen a lot of questions like mine. But none of the answers are working. Anytime I try to update the entity I get an Invalid Column exception: [SqlException (0x80131904): Invalid column name 'ssma$rowid'. Invalid column name 'ssma$rowid'.] Where is this coming from? I have regenerated/rebuilt/cleaned/dropped table and...

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

c#,.net,json,asp.net-web-api
Here is the scenario. There is an web api put call to change an object in sql server database. We want only to change the fields on the database object if they were explicitly specified on webapi call json. For example: { "Name":"newName", "Colour":null } That should change the Name...

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

mysql,.net,database,vb.net,sql-injection
I am using vb.net in Visual Basic 2010 and using Query to edit my Online MySQL Database from the application (WinForms). Here is a sample to insert a new user into the database: MySQLCon.Open() Dim SQLADD As String = "INSERT INTO members(member,gamertag,role) VALUES('" & memberToAdd.Text & "','" & membersGamertag.Text &...

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

asp.net,.net,owin,katana
I'm hosting SignalR in an OWIN selfhosted app - in Azure, like so: public class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(); } ... Easy enough, works fine. Exposes /signalr/hubs as expected. What I would like to do is prevent an HTTP 403.14 when someone hits the / url....

OpenXml.WordProcessing.Justification always comes as OpenXmlUnknownElement

.net,ms-office,openxml,openxml-sdk
I'm building a table using OpenXml and setting the Justification property for every cell. It doesn't really matter where I assign this property, either in the Run element or as a TableCellProperty, when the document is open using the Productivity Tool for MS Office the Justification element always comes as...

.NET use IIF to assign value to different variables

.net,vb.net,conditional,variable-assignment,iif
Could I (and if so how) do the following in .NET language (more specifically VB.NET): Dim a,b as Integer if(somecondition=1,a,b) = 12345 Or any variant with IIF would be fine by me. Basically I'm always assign the same value but never to the same variable.....

inconsistent timing from .net StopWatch

c#,.net,timing,stopwatch,cudafy.net
I have a C# & .NET application that uses a GPU (NVIDA GTX980) to do image processing. There are 4 stages and I synch the CPU to the GPU (no overlap in time) to do timing. But the numbers do not add up. Launch() will do a async launch of...

Formatting large numbers in C#

c#,.net,unity3d,formatting
I am using Unity to make an "Incremental Game" also known as an "Idle Game" and I am trying to format large numbers. For example, when gold gets to say 1000 or more, it will display as Gold: 1k instead of Gold: 1000. using UnityEngine; using System.Collections; public class Click...

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

c#,.net,string,string-comparison
Following is the code snippet from a console application - class MyClass { public int GetDay(string data22) { int returnValue = 0; if (string.Compare(data22,"THURSDAY") == 0) // true { returnValue = (int)DayOfWeek.Thursday; } if (data22 == "THURSDAY") //false { returnValue = (int)DayOfWeek.Thursday; } if (string.Equals(data22, "THURSDAY"))//false { returnValue = (int)DayOfWeek.Thursday;...

Continuous deployment and running with TeamCiy

.net,continuous-integration,teamcity,exe,continuous-deployment
I have a project that is built into an executable. Some kind of server. And a Team City as CI. I configured Team City to automatically build my sources. I would like to achive the following steps: Sources are built by Team City when someone commits into repo. (done) Built...

DialogBox with value verifications

c#,.net,winforms
For my application which deals with graphics, I've made a little DialogBox to set: Max; Min; Major Step (of the scale); Minor Step. Here's a screen capture: I want to validate a few things before allowing the user to click Ok: Max >= Min MaxScale >= MinScale. But it's not...

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

c#,.net,youtube,youtube-api,google-client-login
This is my code in form1: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using Google.GData.Client; using Google.GData.Extensions; using Google.GData.YouTube; using Google.GData.Extensions.MediaRss; using Google.YouTube; namespace YouTube_Manager { public partial class Form1 : Form { YouTubeRequestSettings settings; YouTubeRequest request; string username...

Notify winforms application by Sql Server database changes

c#,.net,sql-server,winforms,sqldependency
I created a Sql server database, in which I added a table named user. Then I executed this script ALTER DATABASE [TestNotification] SET ENABLE_BROKER I'd like to use SqlDependency class to notify a winforms application when the user table were changed. namespace Watcher { public partial class Form1 : Form...

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

c#,.net,zipfile
I have a project which runs fine on 4.0, however in the interests of utilizing the new ZipFile class I have decided to target 4.5. The vast majority of my users will have 4.5+ installed, but its not impossible someone with only 4.0 may come along and try to use...

Does MongoDB successful insert guarantee populated ID's?

c#,.net,mongodb-csharp,mongodb-csharp-2.0
We are using the MongoDB C# driver to insert a collection of records using InsertManyAsync. We currently have code that iterates the entire collection after InsertManyAsync returns, confirming that the ID's are populated. I would expect that the driver takes care of this already, but I have not found documentation...

Check whether print command success or not

c#,.net,winforms,printing
I am printing some PDF files through c# code. My code looks like this myPrinters.SetDefaultPrinter(pdfPrinterName); var info = new ProcessStartInfo { Verb = "Print", FileName = file, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden }; var p = new Process { StartInfo = info }; p.Start(); p.WaitForInputIdle(); System.Threading.Thread.Sleep(18000); if (!p.CloseMainWindow()) p.Kill();...

Custom drawing using System.Windows.Forms.BorderStyle?

c#,.net,vb.net,winforms,custom-controls
I want to mimick drawing of default border based on value of property BorderStyle. Instead of single border around the control, my control is visualised as four adjacent custom-drawn boxes (2×2), each having standard border drawn individually. So for example, if Control.Border is set to FixedSingle value I want to...

Replace string :"{ using regex

.net,regex,replace
I have following string. str= ""10":"{\"read\":\"1\",\"write\":\"0\"}""; Now I want to replace string with :"{ to :{ and }" to } in above string using regex expression. Can anyone guide me to replace the character using regex or can use only replace method....

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

c#,.net,windows,sendkeys
I need to save a file which is in an External application using SendKeys.Send() method. The keys needed to be sent are Ctrl+S. I wrote the below code, but its not working: SendKeys.SendWait("^%s?"); // to get the Save As dialog Thread.Sleep(5000); SetForegroundWindow(FindWindow(null, "Save As")); Thread.Sleep(5000); SendKeys.SendWait("xyz"); // Sending FileName ...

Concordion NUnit throws NullReferenceException when discovering test

.net,concordion
I'm new to Concordion and just started trying it out. I downloaded their example "Kickstart" project at https://github.com/concordion/concordion-net-kickstart/releases/tag/v1.2.0 and I also created my own project to get a better sense of how it works. When I attempt to run my tests in both the Kickstart project and my own project...

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

c#,.net
I am sure the answer to this is quite simple but I am trying to write an if statement (C# 5.0) to determine whether or not an anonymous type is empty or not. Here is a simplified version of my code: public void DoSomething(object attributes) { // This is the...

Web API - Set each thread with the HttpRequestMessage id?

c#,.net,multithreading,task-parallel-library,web-api
I have a web api coded in c#. The web api uses functionality which is shared with other in-house components. it depends on single threaded flows and uses thread local storage to store objects, and session information. Please don't say if it's good or bad, that's what I have to...