Error when trying to populate listbox - c#-3.0

Hi I am a student I am getting this error:
forreach statement cannot operate on
variables of type 'object' because
'object' does not contain a public
definition for 'GetEnumerator'
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;
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string result = " ";
foreach (string activity in listBox1.SelectedItems)
{
result += activity + " ";
}
this.textBox1.Text = result;
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add(textBox2.Text);
textBox2.Clear();
}
}
}
Pl. help me

Your code works fine for me. However, your code will break if you've added something other than a string to your ListBox's Items collection (although this will produce a different error than what you're apparently seeing).
Can you add the code you use to populate this ListBox?

Related

Screen sharing with powershell

i am trying to make a screen viewer.
i have an C# server side that works good and i have C# client side that works good.
this is my C# client side code:
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 System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Drawing.Imaging;
using System.Runtime.Serialization.Formatters.Binary;
namespace WindowsFormsApp24
{
public partial class Form1 : Form
{
private readonly TcpClient client = new TcpClient();
private NetworkStream mainStream;
private int portNumber;
private static Image GrabDesktop()
{
Rectangle bound = Screen.PrimaryScreen.Bounds;
Bitmap screenshot = new Bitmap(bound.Width, bound.Height, PixelFormat.Format32bppArgb);
Graphics graphics = Graphics.FromImage(screenshot);
graphics.CopyFromScreen(bound.X, bound.Y, 0, 0, bound.Size, CopyPixelOperation.SourceCopy);
return screenshot;
}
private void SendDesktopImage()
{
BinaryFormatter binFormatter = new BinaryFormatter();
mainStream = client.GetStream();
binFormatter.Serialize(mainStream, GrabDesktop());
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
portNumber = 443;
try
{
string ip = "192.168.1.55";
client.Connect(ip, portNumber);
}
catch
{
}
timer1.Start();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void btnConnect_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
SendDesktopImage();
}
}
}
The thing i am trying to do, is to switch the client side from C# to powershell.
is that possible? i am searching for ideas on google for along time, I would be happy
to hear what you have to say.. many thanks.
C# and Powershell are both using some version of the Dot Net runtime so the same objects and properties should be available in both, just by a different syntax. The process for converting between the two is basically this:
First you need to load the required assemblies into powershell with Add-Type. You will require several assemblies such as System.Net, System.Drawing and System.Windows.Forms to get access to the Objects in your code. (this is essentially the same as adding references to a C# project). Example: Add-Type -AssemblyName System.Drawing; would load everything inside System.Drawing.dll
Next you need to convert the syntax from C# to powershell line by line:
Example
private readonly TcpClient client = new TcpClient();
Would become:
[System.Net.Sockets.TcpClient] $client = New-Object System.Net.Sockets.TcpClient
Mostly this process will be simplification and expanding names. Above [System.Net.Sockets.TcpClient] is the fully qualified type - ie the long form name of the C# Class (visible on the tooltips in Visual Studio). New-Object is equivalent to new
Assuming you just want the screenshot to be taken and sent each time the script is executed you dont need to worry about writing classes or functions in powershell you can just convert each functional line of c# into powershell in a text file saved with .ps1 extension.

multiply two input boxes and then show result time nine in third box

I am trying to find code to make a calculator of sorts. I need it to be three input boxes where you can type data in the first two boxes. First box divided by the second box and the result is then multiplied by 9 (the nine not shown) and the result or answer is shown in the third text box. With some sort of compute or calculate button.
This should do it:
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;
namespace calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int answer = (Convert.ToInt32(txt1.Text) / Convert.ToInt32(txt2.Text)) * 9 ;
txtAnswer.Text = Convert.ToString(answer);
}
}
}

Token Based Authentication using ASP.NET Web API 2, Owin, AspNet.Identity.MongoDB and mongocsharpdriver

+after successfully implementing Token Based Authentication using ASP.NET Web API 2, Owin, and Identity, i wished to change my implementation to use MongoDB instead of MSSQL with Entity Framework, with the help of this application here....truth be said, i dont fully understand how this should be done, but at least i know what i want my application to behave. i want to follow this IMPLEMENTATION HERE, using AspNet.Identity.MongoDB and mongocsharpdriver...and so far, here,s what I've done:
Account Controller
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using withMongoDB.HelperClasses.Services;
using withMongoDB.Models.Account;
namespace withMongoDB.Controllers
{
[RoutePrefix("api/Account")]
public class AccountsController : ApiController
{
AccountsService _accountsService = new AccountsService();
// POST api/Account/Register
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(UserModel userModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
await _accountsService.Register(userModel);
return Ok();
}
private IHttpActionResult GetErrorResult(IdentityResult result)
{
if (result == null)
{
return InternalServerError();
}
if (!result.Succeeded)
{
if (result.Errors != null)
{
foreach (string error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
if (ModelState.IsValid)
{
// No ModelState errors are available to send, so just return an empty BadRequest.
return BadRequest();
}
return BadRequest(ModelState);
}
return null;
}
}
}
then the register method from the controller should be taken by the accounts Service
using AspNet.Identity.MongoDB;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using withMongoDB.Models.Account;
namespace withMongoDB.HelperClasses.Services
{
public class AccountsService
{
private readonly MongoAccountsConnectionHelper<UserProfile> _accounts;
public AccountsService()
{
_accounts = new MongoAccountsConnectionHelper<UserProfile>();
}
public async Task<IdentityResult> Register(UserModel userModel)
{
var userprofile = new UserProfile
{
UserName = userModel.UserName
};
var result = await _accounts.CreateAsync(userprofile, userModel.Password);
return result;
}
}
}
and finally the MongoAccountsConnectionHelper takes the result of the accounts service class to mongo database....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace withMongoDB.HelperClasses
{
using AspNet.Identity.MongoDB;
//using Entities;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using System.Configuration;
using withMongoDB.Models.Account;
public class MongoAccountsConnectionHelper
{
private readonly MongoCollection<UserProfile> userProfileCollection;
public MongoDatabase Database { get; private set; }
public MongoAccountsConnectionHelper()
{
var pack = new ConventionPack()
{
new CamelCaseElementNameConvention(),
new EnumRepresentationConvention(BsonType.String)
};
ConventionRegistry.Register("CamelCaseConvensions", pack, t => true);
var mongoUrlBuilder = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
Database = new MongoClient().GetServer().GetDatabase(mongoUrlBuilder.DatabaseName);
userProfileCollection = Database.GetCollection<UserProfile>("users");
}
public MongoCollection<UserProfile> Users
{
get { return userProfileCollection; }
}
}
}
any help, tips, ideas, or opinions will be highly appreciated....{should i consider alternatives like MembershipReboot and IdentityReboot by brockallen?}
To do it smoothly, you need first to remove the dependency on "Microsoft.AspNet.Identity.EntityFramework", by providing your own user class/table (which should implements IUser as a minimum), and Also you need to implement the UserManager class (which should imeplements UserManager, and finally you need to implement the UserStore class (which should implement IUserStore as minimum) where T is the Id type in the User Table.
Once you done the above, then it is the UserStore where you can change to use MongoDB.
Hope that helps.

MEF giving CompositionException

I am new to MEF and I am trying this following program.
The class library whose dll I am making has following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.Composition;
namespace MefTestsCore
{
[Export (typeof(MefTestsCore.IFace))]
public class CoreClass1 : IFace
{
public String getName()
{
return "CoreClass1";
}
}
interface IFace
{
String getName();
}
}
The program which wants to access the dll has following code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using MefTestsCore;
namespace MefTests
{
class Program
{
[Import (typeof(MefTestsCore.IFace), AllowRecomposition=true)]
public IFace iFaceObj;
static void Main(string[] args)
{
Program p = new Program();
p.Method();
}
public void Method()
{
DirectoryCatalog catalog = new DirectoryCatalog(#"C:\Users\username");
CompositionContainer container = new CompositionContainer(catalog);
container.ComposeParts(this);
Console.WriteLine(iFaceObj.getName());
Console.ReadKey();
}
}
}
I have the MEFLibrary.dll (dll containing MefTestsCore namespace, the first part of above code) at C:\Users\username. When I run the program, it throws CompositionException with following details
The composition produced a single composition error.
The root cause is provided below. Review the CompositionException.Errors property for more detailed information.
1) The export 'MefTestsCore.CoreClass1 (ContractName="MefTestsCore.IFace")' is not assignable to type 'MefTestsCore.IFace'.
Resulting in: Cannot set import 'MefTests.Program.iFaceObj (ContractName="MefTestsCore.IFace")' on part 'MefTests.Program'.
Element: MefTests.Program.iFaceObj (ContractName="MefTestsCore.IFace") --> MefTests.Program
In your test program you are using MefTestsCore. So I assume you referenced that assembly from your test program. But then you also load a copy from c:\Users\username. Now they types don't match because they come from different assemblies.
You have to put the interface into it's own assembly so that you then can reference it from your program and from MefTestsCore.

Adding Custom Filters for Dynamic Data Website (VS2010, EF4)

Trying to add some different filters (in addition to the ForeignKey filter) to a Dynamic Data Website in VS2010 using EF4. I can add the new Filter templates, but how do I specify which template will get displayed for each property in my model?
Thanks
Here are the steps for how to do this:
1) Create a new UserControl for the filter you want under DynamicData\Filters. I created a TextFilter.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="TextFilter.ascx.cs" Inherits="Test.Prototype.Web.DynamicData.DynamicData.Filters.TextFilter" %>
<asp:TextBox runat="server" ID="TextBox1" AutoPostBack="true" OnTextChanged="TextBox1_OnTextChanged" CssClass="DDFilter">
</asp:TextBox>
and the code behind:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Web.DynamicData;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Test.Prototype.Web.DynamicData.DynamicData.Filters
{
public partial class TextFilter : System.Web.DynamicData.QueryableFilterUserControl
{
private const string NullValueString = "[null]";
protected void Page_Load(object sender, EventArgs e)
{
}
public override Control FilterControl
{
get
{
return TextBox1;
}
}
protected void TextBox1_OnTextChanged(object sender, EventArgs e)
{
OnFilterChanged();
}
public override IQueryable GetQueryable(IQueryable source)
{
string selectedValue = TextBox1.Text;
if (String.IsNullOrEmpty(selectedValue))
{
return source;
}
object value = selectedValue;
if (selectedValue == NullValueString)
{
value = null;
}
if (DefaultValues != null)
{
DefaultValues[Column.Name] = value;
}
return ApplyEqualityFilter(source, Column.Name, value);
}
}
}
Then in your model, just annotate your properties with the FilterUIHint attribute pointing to the next filter and you're good to go:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
namespace Test.Model
{
public partial class Asset
{
#region Primitive Properties
public virtual int Id
{
get;
set;
}
[FilterUIHint("TextFilter")]
public virtual string Name
{
get;
set;
}
...