spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
  Home » C# » Page 5
Unit of Work with StructureMap 3
It is very bad idea to use singleton for dbcontext in web application. You should consider to change this to PerHttpRequest lifecycle (if it exists in structuremap) or PerResolve lifecycle: Per HttpRequest: For<IUnitOfWork>().LifecycleIs(new HttpContextLifecycle()).Use<PortalDbContext>(); Update: in this case, you should not use your IUnitOfWork in using statement and lay responsib

Categories : C#

Not getting data-val attributes for GUID
Firstly, I would want to know what the problem is with having multiple GUID data annotations on your model properties? Secondly I would say that it is far clearer and readable to other developers working on the project to have explicit validation going on with data annotations on each property than it is to have some "non-standard" validation voodoo going on. You could probably achieve this with

Categories : C#

What is my mistake in implementing Foreign Key with EF 6?
Your navigation-property is not virtual and thus cannot be overridden by the DynamicProxy. Change it like this: public class Person { public int Id { get; set; } public virtual ICollection<Anime> DirectedAnimes { get; set; } } public class Anime { public int Id { get; set; } public int DirectorId { get; set; } public virtual Person Director { get; set; } }

Categories : C#

Is it necessary to mock all and every dependency in Unit Tests?
No, you don't. The different concepts of test object implementations you can use are known as Test Doubles. Mocks are just one type of Test Double as defined by Gerard Meszaros in his book: Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists. Fake objects actually have working implementations, but usually take some shortcut which makes t

Categories : C#

EF Code First many-to-many: how to specify name of th third table and add some other properties to it?
Since you need to add additional properties to describe the relationship, you have to consider many-to-many association as two one-to many ones: public class User { // other properties omitted public virtual List<UserRole> UserRoles { get; set; } } public class Roles { // other properties omitted public virtual List<UserRole> UserRoles { get; set; } } public class Us

Categories : C#

How do you ignore Whitespace when using CsvHelper, CsvReader.Read()?
I think your best bet is to fix the library yourself. The problem is that the Read method uses the SkipEmptyRecords setting and the IsRecordEmpty method to determine if it should skip a field or not: while (this.configuration.SkipEmptyRecords && this.IsRecordEmpty(false)); However the IsRecordEmpty() method is not perfectly implemented to support your scenario, because it uses the foll

Categories : C#

WepApi Route and RoutePrefix Confusion
With your configuration, the correct URL would be /Api/Portal/User/5cbcec52-f417-48a2-a241-470e48518858 If you want to use the other Url, you have to change your controller method as follow: [Route("{accountId:guid}")] public JsonResponse<UserDto> Get([FromUri]Guid accountId) { return new JsonResponse<UserDto>("Success", true); } The parameter attribute [FromUri] defines whe

Categories : C#

Could not load file or assembly, system could not find the file specified
Couple of tips - hard to know if they'll help you: Open the csproj file(s) in a text editor and see where the dlls are being referenced (GAC possibly) If it's a signed assembly, make sure you've got a signed copy (if you've built an Open Source project yourself the signing will be lost) Look at the references in Visual Studio - do you have Copy Local set to True and Specific Version set

Categories : C#

DataTemplate is not drawn, wpf
You create MyPerson after InitializeComponent, which also sets DataContext to MainWindow as specified in XAML, and since your property does not raise INotifyPropertyChanged.PropertyChanged event UI is never notified that it has changed. You can either implement INotifyPropertyChanged on MainWindow and raise PropertyChanged event for MyPerson property or if that property does not change, only its p

Categories : C#

How to navigate from ContentPage to ContentPage?
Answer taken from Xamarin.Forms documation here listView.ItemSelected += async (sender, e) => { var todoItem = (TodoItem)e.SelectedItem; var todoPage = new TodoItemPage(todoItem); // so the new page shows correct data await Navigation.PushAsync(todoPage); }; So for you, it would probably look something like this: PageManager.WelcomePage.OnLoginEnter += () => { aw

Categories : C#

WFP BackgroundWorker waits to other BackgroundWorker to finish
First thing is, maybe you can do all the background work in 1 BackgroundWorker. To answer your question, you can start the 2nd BackgroundWorker in the 1st's RunWorkerCompleted event handler. bw1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw1_RunWorkerCompleted); private void bw1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //celebration! //and then s

Categories : C#

Issue in updating MS Access records using oledbcommand.executeNonQuery(), result not updating
OleDbCommand doesn't support named parameters. The only matter is their orders. From OleDbCommand.Parameters property The OLE DB .NET Provider does not support named parameters for passing parameters... Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the para

Categories : C#

Change JSON.net content via property name?
Here's a converter that will handle it, at least for simple objects as per your example. It looks for objects containing objId properties and then serialises all properties it finds on them. You may need to expand it to deal with other member types/more complex properties as required: class MyConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSer

Categories : C#

Can you change an object while it is being serialized and does that affect the serialization result?
This is rather a problem with concurrency, not so much about serialisation. If you have one thread changing the object while another thread is reading from it, the result will be corrupted data. You need to synchronise the access to the object so that reading and changing it at the same time is not possible.

Categories : C#

Enterprise Architect Date format for storing DateTime type tagged value
I actually don't know anything about Enterprise Architect but I would guess.. In which format Enterprise Architect stores the values for DateTime type tagged values,in some cases it stores in d/M/yyyy or M/d/yyyy format. A DateTime doesn't have any implicit format. It just has date and time values. Textual representatsion of a DateTime (also called string representation) can have a forma

Categories : C#

Multithreading in C# does not start
There are several problems with your code. You're accessing the UI in a worker thread, which isn't legal. You create new threads each time TextChanged fires and forgetting about the thread(s) created earlier. You're using the wrong data structure. Etc If you use the right tool, then you don't need a thread at all. You should be using Trie data structure for searching items that starts with exp

Categories : C#

how to display the content of a structure in a listbox in a c# windows form application
Since you wrote that your structure is defined elsewhere I asume you can't change it. The usual way to get a custom made display string is to wrap your structure in a minimal class, maybe like this: class FT_DEVICE_wrapper { public FT_DEVICE_LIST_INFO_NODE INFO_NODE { get; set; } public FT_DEVICE_wrapper(FT_DEVICE_LIST_INFO_NODE data_) { INFO_NODE = data_; } public override str

Categories : C#

How to remove the last DataGridViewRow when inserting a new one at the beginning?
try to change this if (this.Rows.Count > maxRowsAllowed) { this.Rows.RemoveAt(maxRowsAllowed); } to this if (this.Rows.Count > maxRowsAllowed) { // if the number of rows is 10 // the index of the last item is 9 // index 10 is out of range this.Rows.RemoveAt(maxRowsAllowed -1); }

Categories : C#

Stop SQL Server service on application install
You should specify service's name e.g. MSSQLSERVER, not its display name SQL Server (MSSQLSERVER). Here is a List of SQL Server Service Names.

Categories : C#

0 rows inserted with Entity Framework
Ok, so the problem is fixed and it was due to my lack of knowledge. So apparently @MilenPavlov was right. I did in fact inspect a different database. I had no idea that when built the project copies the *.sdf to DEBUG folder and places changes there - courtesy of Copy to Output Directory property on your *.sdf file. So as I was inspecting via Visual Studio, I've been viewing a different copy of th

Categories : C#

How do I check is uptime value on datasource with C#
Assuming there will only be a mention of days when the uptime is one day or larger: if (drv["uptime"].ToString().Contains("day")) { // up for one day or more } else { // not up for a day yet }

Categories : C#

Parsing CSV data
// Add Microsoft.VisualBasic.dll to References. using Microsoft.VisualBasic.FileIO; // input is your original line from csv. // Remove starting and ending quotes. input = input.Remove(0, 1); input = input.Remove(input.Length - 1); // Replace double quotes with single quotes. input = input.Replace("""", """); string[] result; using (var csvParser = new TextFieldParser(new StringReader(input)))

Categories : C#

Split each element of an IEnumerable list using MVC4
you can do it like this: @model ERP.ViewModels.PlotSelector @{ var temp = Model.Plot.Split(','); } @foreach(var item in temp) { <tr> <td> @Html.EditorFor(i => i.Select) @Html.HiddenFor(i => i.QuoteProductID) </td> <td> @Html.Display(item) </td> </tr> }

Categories : C#

Logging to NLog in Hangfire.io
I have managed to solve this issue by using the following versions of nuget packages: NLog - 3.1 Common.Logging - 2.2.0 JVW.Logging.CommonLoggingNLogAdapter - 1.0.0.1 and then configuring the logging as such var properties = new NameValueCollection(); properties["configType"] = "INLINE"; Common.Logging.LogManager.Adapter = new NLogFactoryAdapter(properties);

Categories : C#

NullReferenceException when calling Controller.Execute
I am able to execute your code without any exception though the exact scenario in your case could be different. I am not sure, if you did it already, and if you are doing this in Visual Studio then: 1) Wrap the code: controller.Execute(ctx); in a try...catch block so that you should be able to see the exception detail. You can click the "View Detail" at the bottom of exception window so that you

Categories : C#

How create exe file with resources by Visual Studio 2013
It is not enough to Copy to Output Directory your resources - this will result in copying the files into the build output folder on your development machine. The simplest approach in you case would be to embed the files into the executable itself using Embedded Resource build action for each of them: Then, you would access the files like described here. Note As David pointed out in the commen

Categories : C#

windows RT / Universal app, Text to speech "Save as Mp3"
I think you can save SpeechSynthesisStream as just a .wav file. Then you can re-encode it to anything you like using a MediaTranscoder class. MSDN: Media Transcoder Sample Project using Media Transcoder -- use it as a refeence Some extra help saving the stream to a wav file : SpeakText.xaml.cpp

Categories : C#

Alexa TopSites - Continuous Signature Failures - C# Implementation
Based on Darrel's comment and extensive comparisons between requests from the Java app and my sample app I've been able to correctly query the services using a number of requests including the sample one above. It would appear to have been a problem whereby the request string which is signed had an erroneous space character in front of the hostname, for added resiliency I am using the Amazon AWS

Categories : C#

Can I save an EXCEL worksheet as CSV via ClosedXML?
No, it is not possible directly in ClosedXML. You have to use loops or LINQ to build your own CSV file. For example: System.IO.File.WriteAllLines(csvFileName, worksheet.RowsUsed().Select(row => string.Join(";", row.Cells(1, row.LastCellUsed(false).Address.ColumnNumber) .Select(cell => cell.GetValue<string>())) ));

Categories : C#

DataGridRow.IsEditing never returns true
It was little tricky. I needed to add the below lines to my code to make it work: dg.CurrentCell = new DataGridCellInfo(dg.Items[rowIndex], dg.Columns[0]); dg.BeginEdit(); So, now my complete code looks like: dg.CurrentCell = new DataGridCellInfo(dg.Items[rowIndex], dg.Columns[0]); dg.BeginEdit(); for (int column = 0; column <= dg.Columns.Count - 1; column++) { if (!(GetDataGridCell(ne

Categories : C#

Account freeze for some seconds
There are a lot of ways to freeze an account. You can set up a permissions list. Inside the permissions list you could set a token and increment it every time someone tries to login. If the value of the token is in excess of some value the user can't log in for sometime frame as determined by a DateTimesetting. What have you tried if anything? Do you have any code you can share so the users can u

Categories : C#

GroupBy in LINQ return me invalid values using Entity Framework 4.0
GroupBy returns IEnumerable where IGrouping has Key of type x.Key and Value of type IEnumerable, where T is type of x (not a string) To get what you want you should use: var availName = dataContext.sp_GetAvailable(1).ToList().GroupBy(x => x.TXT_NAME).Select(x => new { Name= x.Key, Communication = string.Join(",", x.Select(c=>c.Number)) })

Categories : C#

How to use Sum method conditionally in Select section in LINQ
I got the true way, so I put my way here for you guys ! var query = from comment in SH_Comments join user in Users on comment.UserID equals user.UserID join product in SH_Products on comment.ProductID equals product.ID join vote in SH_CommentVotes on comment.ID equals vote.CommentID group comment by new { comment.Body,

Categories : C#

Setting each ListViewEntry with a different font
The Constructor new Font(FontFamily fontFamily, Float fontSize); automatically sets the Font Style as "regular". However, not all Fonts actually support the Regular Style. Better results can be achieved by checking the FontStyle-enumerator: if (fontFamilies[i].IsStyleAvailable(FontStyle.Regular)) familyList[i].Font = new Font(fontFamilies[i], 12); else if (fontFamilies[i].IsStyleAvailable(F

Categories : C#

Can WebAPI change output just before response?
I think you have to create customer attribute. Decorate all your action or controller with that attribute. In that on you have to read result and deserialize back to Json object or .net object. Following link will help you on that. http://damienbod.wordpress.com/2014/01/04/web-api-2-using-actionfilterattribute-overrideactionfiltersattribute-and-ioc-injection/

Categories : C#

Need help converting PowerShell to C# code
I was unable to find a way resolve this issue and no one seems to have an answer. So I've solved this by using NETDOM when Server RPC is unavailable. (Exception HRESULT: 0x800706BA) actually any error happens I will add access denied check so it won't try NETDOM when this happens; var remoteControlObject = new ManagementPath { ClassName = "Win32_ComputerSystem", Server = oldName, Pat

Categories : C#

OrderBy List by another collection
Something like this, though with mutiple authors it remains a question which author you order by: var sorted = from book in b let firstAuthor = book.BookAuthors.First() let lastName = firstAuthor.LastName order book by lastName select book Alternatively you could apply some logic (if you had it)... var sorted = from book in b let author = book.BookAuthors.FirstOr

Categories : C#

Why can't a constant field be of non-built-in struct type in C#?
Fundamentally, true constant fields need to be representable directly in IL as metadata, which means: limiting to a set of known types that work directly in IL. You could say that you can express a "constant" via a constructor call and substitute that constructor call whenever the constant is used, etc, but: that would be simulating something very close to static readonly, which already exists a

Categories : C#

Containing ASP.NET Identity in StructureMap's IoC
I have not used StructureMap massively, but your registration looks wrong to me. You register delegates instead of letting the container to deal with that. Instead of using delegates do the type registrations: For<ApplicationUserManager>().TheDefaultIsConcreteType<ApplicationUserManager>(); And change all the rest of the registration to be this way (see documentation for more explan

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.