C#

94K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

Share tech news, updates, or what's on your mind.

Sign up to Post

Hi
Building on an earlier question

I'm trying to create a Winforms Application

Although related I've split this into 2 questions

I can run a query and add a list of All movie titles into a listview but when I click an item I cannot access movie properties to populate the form elements adding a watch to movie
MovieID.JPG
MovieID1.JPG
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 MoviesDataModel;

namespace FilmsDB
{
    public partial class Form1 : Form
    {
        public string ImgPath = @"E:\Media\thumbs\Movies\";
        public Form1()
        {
            InitializeComponent();
            TitlesLV.View = View.Details;
            ColumnHeader columnHeader = new ColumnHeader();
            columnHeader.Text = "Film Title";
            columnHeader.TextAlign = HorizontalAlignment.Center;
            columnHeader.Width = -2;

            TitlesLV.Columns.Add(columnHeader);
            LoadMovies();
        }

        private void LoadMovies()
        {
            TitlesLV.Items.Clear();
            using (var context = new MoviesEntities())
            {
                //get a full list of all movies (will return everything from 

Open in new window

0
HTML5 and CSS3 Fundamentals
LVL 13
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

Hi,

My response[0].Body[0].Content has the following value:
{"title":"StudentRecord", "students":[
					{"name":"Josh", "age":"45", "sex":"male}, 
					{"name":"James", "age":"18", "sex":"male}, 
					{"name":"Emily", "age":"25", "sex":"female}, 
					{"name":"Nate", "age":"33", "sex":"male}, 
					{"name":"Nichole", "age":"19", "sex":"female}, 
					{"name":"Janet", "age":"21", "sex":"female}
				      ]
}

Open in new window

What I want to do is remove all the students but the first and last ones from students array so that the result becomes
{"title":"StudentRecord", "students":[
					{"name":"Josh", "age":"45", "sex":"male}, 
					{"name":"Janet", "age":"21", "sex":"female}
				      ]
}

Open in new window


I tried like
var myObj = Newtonsoft.Json.Linq.JObject.Parse(response[0].Bocy[0].Content.ToString());
I know how to remove a property totally, but not partial values from the array.
I am also not sure if I have to convert it to JObject first since then I have to convert it back to the original type of response.

Is there any easier way to solve this issue?
0
I need to add grouping to this method:

[HttpPost]
        public JsonResult GetData(string variable1, string variable2, string variable3)
        {
            string[] reportData = (from x in DB.GetDetails().ToList()
                            where x.field1 == variable1
                            && x.field2 == variable2
                            && x.field3 == variable3
                            select x.field4).ToArray();

            return Json(new { option = reportData });
        }

Open in new window


I get duplicate values and need to group the data or add a Distince to the reportData.  I'm not sure how to go about this.  Thanks for any help!
0
Hello,

I need to load data on scroll. So is there any option i can use. I am using windows form .NET normal dropdown but  if i just load data  , as the data is very large it takes lot of time. I am thinking to load data or items in dropdown on scroll. Not getting any option. Please suggest if anything i can use.

Thanks.
Abhilash
0
Hi

I'm using an SQLite  database which doesn't  play nice with Entity Framework

I've been enhancing a previous question here  

in SQL to use LIKE you need to use the '%' wild card eg

Select * from movie where title like '%Big%'

Open in new window


In the code bellow I'm building the query thus
string fName = "%" + Path.GetFileNameWithoutExtension( fi.Name) + "%";

Open in new window

and sending that as a Parameter
Is that the best to do it?

The main part of my question is how do I return a list of movies instead of the last one wins?

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

using System.Configuration;
using System.Data.SQLite;

using System.Diagnostics;

namespace UpdateMoviePath
{
    class Program
    {
        public class MovieObj
        {
            public int Id { get; set; }
            public string Title { get; set; }
            public int Year { get; set; }
            public int FileId { get; set; }
            public string FilePath { get; set; }

        }
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            string Films = @"E:\Media\TestFilms";

            if (Directory.Exists(Films))
            {
                string[] Files = Directory.GetFiles(Films, "*.mp4");
            

Open in new window

0
Hi,

Today I was asked this question:

We have
actualResult.AdditionalInfo[0].Content

Open in new window


Content itself have several properties such as Title, Type, Id, ActionPacks etc.
ActionPacks has 10 elements as
ActionPacks[0], ActionPacks[1], ActionPacks[2]....ActionPacks{9]

The question was
"how can we know the number of ActionPacks properties?

I answered like
actualResult.AdditionalInfo[0].Content.GetType().GetProperty("ActionPacks").Count

Open in new window

I know it's wrong.

Is there anyway I can find out the number of elements in ActionPacks?

Is this question even valid considering no additional information is given?
0
I use datalayer In VS C# to create table but I drop the table first. I get an error if the table does not exist and give the drop command. . Dtaaccess.dtabase.execute(drop table tablename)
What is the datalayer method to check if table exist?
0
Hello All,

A project has come up to on demand scan a uploaded document for viruses in our site.
 
Some info on our site:
C#, MVC system with razor templates and xml configurations for custom UI.
AWS hosted web server and db.
Currently the users can attach documents to various items in our system.  Those documents are stored as varbinary in the db tables.


It was suggested to me to look into Clamav.net, but I'm wondering what the best solution (tool) other than Clamav, would be for scanning of a file that goes directly into a db table and not a folder structure on the server?  If it is necessary to save the file in a folder structure in order to do the scanning then we can change the system to do that.

Thank you for your time and suggestions.

Sincerely,
Ex
0
I have a horizontal form that I created in an ASP.NET MVC 5 project with Bootstrap 3 (I know this is an old version and may convert to version 4 later). The form-horizontal form is not fitting the full width of the screen even though I have a total of 12 columns in the class. I'm sure it's a simple fix, I just haven't been able to figure it out. I am not using any custom CSS on this page. Here is part of the code. It just has one of the divs. I can provide full code if needed.

<h2>Create Customer</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Customer</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })


        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

Open in new window

0
I have an application running in ASP.NET/C#/IIS/SQL Server.

The application is not rendering correctly on any browser other than Internet Explorer.

I have added a document with the details on display and some setting changes I had to make for PCI Scan Vulnerabilities.

Please advise on what the issue may be.

Thanks,

Bruce Merevick
GCC-image-issue.docx
0
Fundamentals of JavaScript
LVL 13
Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

I am a newbie to C# and have inherited a web app that I am now solely responsible for fixing and enhancing. I just created a Controller and a view via the VS wizard "MVC 5 Controller with views, using Entity Framework". I am using the default code that VS generated.

I also noticed that the record still comes up even if the ID is the same one as in the SQL View.

Any help would be greatly appreciated!

I have tried to start over and build everything a second time.

This is the controller.
public ActionResult Index(int? id)
{
 
if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); }
ViewBag.ID = id;
return View(db.JD.Where(x=>x.ID ==id).ToList());
}

This is the index.cshtml code
@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.JudgmentID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LoanID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.JudgmentAmount)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.JudgmentDate)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
            @Html.ActionLink("Details", "Details", new { id = item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.ID })
        </td>
    </tr>
}
This is what is displayed. There are actually 3 different records it …
0
Hi

I need to do some file management by creating a new directory for each film and associated files

the new Dir Name will be Film name Year

This information is stored in an SQLite  database which will need updating

In the code bellow I'm trying to pass the SQL query into a method and return a Movie Object I can then use this to create the New Dir etc
BTW The SQL Query is valid, admittedly there maybe a better way to do this however I'm running VS 2015   which doesn't have EF & EF doesn't play nice with SQLite  

I'm running into several errors
Severity	Code	Description	Project	File	Line	Suppression State
Error	CS0029	Cannot implicitly convert type 'string' to 'UpdateMoviePath.Program.MovieObj'	UpdateMoviePath	D:\Vb\Test\UpdateMoviePath\UpdateMoviePath\Program.cs	41	Active

Severity	Code	Description	Project	File	Line	Suppression State
Error	CS0161	'Program.RunQuery(string)': not all code paths return a value	UpdateMoviePath	D:\Vb\Test\UpdateMoviePath\UpdateMoviePath\Program.cs	52	Active

Severity	Code	Description	Project	File	Line	Suppression State
Error	CS0122	'Program.MovieObj.id' is inaccessible due to its protection level	UpdateMoviePath	D:\Vb\Test\UpdateMoviePath\UpdateMoviePath\Program.cs	85	Active

Open in new window


using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

using System.Configuration;
using System.Data.SQLite;

using System.Diagnostics;

Open in new window

0
I have a c#  application in which i am trying to
write values from a list  and a combo  into a grid and later on to  save it.

The grade level is loaded to a  List Box  while
The Entry codes are loaded to a combo (within the Grid)  see  attached screen

Input  Screen showing List and Combo both loaded
I have a problem specifying the the statement that will move the items from the List and Combo
to the Grid.

I believe the first issue  is the fact that the script attached below is not under the right event
as i am not able to address  the Currentrow under this event.

1. Which event should i use to ensure i have access  to the Current row so that my selections
will be writing on the current row

2. I am casting the Model  Proportion Model  to a Combox  ( loaded within the grid )
Is this correct or i should be casting the model to a DataGrid instead  ( see code below )

private void dgvDetailsTable_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                string varentcode = "";
                string varenttype = "";
                var data = (sender as ComboBox).SelectedItem as ProportionsModel;
                varentcode = data.Ent_code;
                varenttype = data.Ent_type;

                Convert.ToString(dgvDetailsTable.CurrentRow.Cells["txtcmbCode"]) = data.Ent_code;
                Convert.ToString(dgvDetailsTable.CurrentRow.Cells["txtenttype"]) = data.Ent_type;
            }
        }

Open in new window


3. What would be correct syntax for the 2 lines flagged as error  (see  screen below)

Error Screen on lines trying to get data from List and combo into the DataGrid
I will appreciate suggestion to enable me resolve this issue

Regards

Olukay
0
Hi Experts,

We have an EDM in our c# app, and we use FileStream/FileTable technology to store documents (Word, PDF, etc.).  We have a database with only 2 filetable tables to make the job. (other data are stored in a second classical db).

One of our db in production was in "Recovery pending status" today, we see a lot of reasons and workaround to fix it.

For this time, we need to detach an reattach it, but it is not satisfactory for us, we want to know why and avoid this issue.

For information and for different reasons, our application needs to open an Office doc (word / excel) from c# and we use the Filetable share directory like \\serveur\instance\FS for that.
A strong constraint is that the user can open the document and save it transparently.

Our questions are:
1. At the moment where the db is in "Recovery pending status", are there any tools or SQL statement to help us to understand the reason?
2. Is there a daily check to be done regularly on the databases to prevent these issues?
3. Of course, this db contains about 50GB to 300GB and important documents, is there a risk of losing the data?
4. What are the usual tools to repair, for example: if we detach the db and we cannot reattach it, what to do?

Thanks a lot for your Help.

With kind regards
Herve
0
I'm trying to add a textview filter box to filter my Scrollview.  Here is the text changed event:
public void _txtFilter_TextChanged(object sender, EventArgs e)
        {
            if (_txtFilter.Text != string.Empty)
            {
                filtertext = _txtFilter.ToString();

                string filePath = Path.Combine(FileSystem.Current.LocalStorage.Path + "inventory.json");
                var jsonContents = System.IO.File.ReadAllText(filePath);
                RootObject instance = JsonConvert.DeserializeObject<RootObject>(jsonContents);
                itemsList = instance.GetInvListResult.Where(u => u.Olditem.ToLower().Contains(filtertext));
                PopulateList();
            }

            else
            {
                PopulateList();
            }

        }

public void PopulateList()
        {
            mainActivity.RunOnUiThread(() =>
            {
                foreach (GetInvListResult item in itemsList)
                {
                    TextView itemTextView = new TextView(mainActivity);
                    itemTextView.Text = item.Olditem;

                    itemTextView.SetBackgroundColor(Android.Graphics.Color.ParseColor("#ffbb001f")); // MIRed

                    itemTextView.SetTextColor(Android.Graphics.Color.White);
                    var parameters = new LinearLayout.LayoutParams(ItemsList.Width, 70);
                    parameters.SetMargins(5, 5, 5, 5);
                    itemTextView.LayoutParameters = 

Open in new window

0
Hi Experts!

Have a User class that implements IComparable<User>. What this gives us is the ability to sort on the list w/o having to create another list by FirstName.

    internal class User : IComparable<User>
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

        public int CompareTo(User other)
        {
            return this.FirstName.CompareTo(other.FirstName);
        }
    }

Open in new window


It looks users.Sort() works, but users.Reverse() doesn't work. Any ideas how to fix this?

Here's the entire code.
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    internal class User : IComparable<User>
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

        public int CompareTo(User other)
        {
            return this.FirstName.CompareTo(other.FirstName);
        }
    }
    
    [TestClass]
    public class UnitTest1
    {
        List<User> users;

        [TestInitialize]
        public void StartUp()
        {
            users = new List<User>()
            {
                new User() {FirstName = "Sally", LastName = "Jones", Age = 30},
                new User() {FirstName = "Yu", LastName = "Lan", Age = 40},
                new User() {FirstName = "Sook", LastName = "Kim", Age = 20},
            

Open in new window

0
I am able to save a Date field in to the database  in the format  "dd-mm-yyyy"
with the statement below:


startdate.Value = DateTime.ParseExact(GridVariables.GridColumn03, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
enddate.Value = DateTime.ParseExact(GridVariables.GridColumn04, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);

However  when trying to get the same data  from the database  it comes back in the format  "yyyy-mm-dd" using the 2 lines below

model.Startdate = (DateTime)reader["Startdate"];  
model.Enddate = (DateTime)reader["Enddate"];

I believe i need a similar clause  with a cultureInfo   statement

Somehow  I have not been able to get the syntax right  particularly with the reader

Can someone please help me to state the equivalent for the read or get operation so that
the output  in my List and DataGrid  are in the format  "dd-mm-yyyy"

Thanks

Olukay
0
We need to build a 64 bit ASP MVC app that can use 64 bit powershell. This is proving to be much harder than we thought. We have successfully built our app in a console using 64 bit debug properties, however when we try to build a new MVC 64bit project, we are getting error upon error.

What we are trying to accomplish is having a self service web page where a user can view an action and click a button. That button will execute a powershell script and provide the user confirmation the task was completed. Something like: [copy file to FTP]. The user clicks the button the PoSh gets executed copying the file to the correct location the user is not aware of, then the user gets output on the webpage stating the file copy was a success.

I feel we are missing something simple here. Does anybody out there have experience building something like this and if so can they point me to a comprehensive web article or book that will show us how to get a 64 bit MVC app working with the following assemblies added:

using System.Management.Automation;
using System.Management.Automation.Runspaces;
using Microsoft.FailoverClusters.PowerShell;

Open in new window

0
I am reading an Excel spreadsheet where one of the columns is date field.  I have to trap for two potential bad dates. "00/00/0000" and "01/01/1900". The code below works fine for "01/01/1900" but crashes for "00/00/0000". What is the proper way to test for bad dates coming from Excel?

                                sDate = xlRange.Cells[i, j].Value2.ToString();
                                ddate = double.Parse(sDate);

                                redistributionLastDate = DateTime.FromOADate(ddate).ToString("yyyyMMdd");

                                if (redistributionLastDate == "18991231" && xlRange.Cells[i, j].Value2.ToString() != "1/1/1900")
                                    redistributionLastDate = "19010101";
0
CompTIA Security+
LVL 13
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

Hi experts,
First of all, I'm not a web developer.
I have a web-host account, a SQL database and a domain name. I need to do the following Max by tomorrow :)
- I need a very simple form consists of 4 or 5 fields to insert data.
- A save button to save data in database.
Or any other method to do the same through my webpage.

Thanks in advance,
Daniel Mina
0
on azure cloud web app service, what is the root directory of the website?
for example, i have website called abc.com\document\  is it like :c:\\IIS\document?
0
I have a json file "inventory.json" file that I am trying to show in an xamarin android listview but am having trouble understanding the adapter.  Here is my code which is throwing this error:  Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ProfilesScan.Model.SelectInvItemlist]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

public class EOMSelectItemActivity : Activity

    {
        public Button _btnSelect;
        public ListView _listView1;
        public TextView _txtFilter;
        public string jsonString;
        public string inventoryitems;
        private ArrayAdapter<string> adapter;
        public string items;
        private List<string> invItems;
                

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate (savedInstanceState);
            SetContentView(Resource.Layout.EOMSelectItem);

            _listView1 = FindViewById<ListView>(Resource.Id.listView1);
            

            string filePath = Path.Combine(FileSystem.Current.LocalStorage.Path + "inventory.json");

            invItems = new List<string>();
            invItems.Add(items);

            var jsonContents = System.IO.File.ReadAllText(filePath);
            items = JsonConvert.DeserializeObject(jsonContents).ToString();

            ArrayAdapter<string> adapter = new 

Open in new window

0
Following on from an earlier question

I've created an Entity Framework MoviesDataModel now I'm struggling to work out how to use it I'm pretty sure it's to do with DbContext

I've created a console app in the same folder with the intention of just printing each movie title
Once I've done that I can then explore how to add a filter using LINQ something like

SELECT title from movie where person.name = 'John Wayne';

But first how do I connect and use the MoviesDataModel?

Writing the code bellow I had no intellisense nor does MovieTest appear in Solution Explorer


using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using MoviesModel;

namespace MovieTest
{
    class Program
    {
        static void Main(string[] args)
        {
            List<MoviesDataModel.movie> movies = new List<MoviesDataModel.movie>();

            foreach (MoviesDataModel.movie movie in MoviesEntities)
            {
                Console.WriteLine(movie.title);
            }
        }
    }
}

Open in new window

0
c# abstract class call base constructor and overload constructor:


    public abstract class AbsAnimationItem
    {
        public AbsAnimationItem(GameObject go)
        {
           ...
        }
    }

 public abstract class AbsAnimationItemRepeatable : AbsAnimationItem
    {
        public AbsAnimationItemRepeatable(GameObject go) : base(go)
        {
            ...
        }
            
        public AbsAnimationItemRepeatable(GameObject go, int numOfRuns) : this(go)
        {
            ...
        }        
    }

public class LightRotation : AbsAnimationItemRepeatable
    {
       public LightRotation(GameObject go) : base(go)
        {
            ...
            SetupRefs();
        }

        public LightRotation(GameObject go, int numOfRuns)[b][u] :this(go) base(go,numOfRuns)[/u][/b]
        {
            ...
        }
}

Open in new window



So, in the last line I want to call base constructor and overload constructor. How do I do this?
0
Hello Experts,
I would like to be able to send emails from my own application
not depending from google gmail or nothing...
just my app sending the email

Is this possible, and if there is an example?
Right now using visual studio basic and visual c#
But we could use anything you suggest.
 As long as it gives us the control and we do not depend on third party services.

the thing is gmail automatically block itself if not used constantly and also present different challenges that change constantly.
Regards!

Just wanted to add that right now our apps send emails programatically using gmail services,
so we want to get rid of that dependance...
Thank you
0

C#

94K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).