Find Role of logged in user and redirect to specific page based on roles

I am pretty new in ASP.NET c#. But i am getting a good hold of it. There are all the time new things a new learner comes up with though and spends hours together finding out a solution.

Here is my issue.

I have a ASP.NET membership setup. I have a asp login system on the website. I have created 2 roles Administrator and Users.

I have 1 user in Administrator and 1 in Users currently for my testing purpose.
Now when the user logs in to the system i want to check there roles and if the role of teh logged in user is Administrator then send them to a specific folder called admin or else send them to the default.aspx in root directory.

How do we find the Role of logged in user and redirect accordingly.

Posted On: Saturday 29th of December 2012 01:27:11 AM Total Views:  2112
View Complete with Replies

Related Messages:

Re: [2.0] Show another form as a dialog (or show a dialog)   (159 Views)
Problem 1: I am wanting to make my own dialog, but I did not see the option in the 'New Item' list in VS C#, so I made a windows form, and set the same settings as a dialog box would normally have, but I can't do myDialogForm.ShowDialog(); it doesn't have the parameters... Problem 2: I can't access any variables from Form1, to myDialogForm, Any Idea's
waht isthe Different java vs C#   (152 Views)
Hi i used to prog with java(in my Unive.) but i don't like its statutes(u cannot access to the memory) so waht isthe Different between java and C# and is it easy for me to prog in C#
Re: Hot-Keys   (152 Views)
I need to make a few hot-keys for my form. I need them to work no matter what control is active and I don't want to have to make an event method for each control to handle a keypress so how do I make a universal hot-key for it
DataGrid & DataBind()   (139 Views)
Why does my DataGrid do not accept DataBind Code: .... string sCnx = "server=..; uid=..; pwd=..; database=.."; SqlConnection cnx = new System.Data.SqlClient.SqlConnection(sCnx); cnx.Open(); SqlCommand cmd = new System.Data.SqlClient.SqlCommand(); cmd.Connection = cnx; cmd.CommandText = "GetInfo"; cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter dataAdapter = new SqlDataAdapter(); dataAdapter.SelectCommand = cmd; DataSet dataSet = new DataSet(); dataAdapter.Fill(dataSet); dgTest.DataSource = procs.GetProc(); dgTest.DataBind(); The error is: 'System.Windows.Forms.DataGrid' does not contain a definition for 'DataBind' How can I fill the DataGrid with the dataSet
Amateur Threading Question   (157 Views)
I have a feeling that I can't figure this one out for myself just 'cause I'm tired again but what the hey at least this one's a quick'un: So I've made a thread within Main and I've started it up, it's all working funky but now I want to be able to detect when Main has finished executing from the newly started thread. I know I need to use IsAlive but I'm not sure how to refer to Main or what the name of Main's thread is, if that makes sense
QueryPerformance   (143 Views)
Can anybody explain to me why the following four red lines of code yield different results to their purple line counterparts By my reckoning the results should be te same but one set are printed to the console window and the other to a text file. The purple lines are definitely creating correct results because they are a product of help code for Microsoft Visual Studio .NET and the results look good. The red lines of code (my code) are definitely producing incorrect results and all four of the outputs are often identical. Am I doing some memory management incorrectly Code: #include "stdafx.h" #using #include #include #include using namespace System; // This is the entry point for this application int _tmain(void) { _int64 ctr1 = 0, ctr2 = 0, freq = 0; int acc = 0, i = 0; FILE *storage; //Start timing the code if(QueryPerformanceCounter((LARGE_INTEGER *)&ctr1) != 0) { storage = fopen("C:\\TestTimer.txt", "a"); //Open a file for data output //Code segment is being timed for(i=0; i
Passing ImageList between forms   (180 Views)
I have two forms frmMain and frmUsers. frmMain has an ImageList, and I fill that list with pics from file when program starts. However I need to use the pics from the ImageList on my other form. How can I use the ImageList from frmMain in my other form
Re: Getting error that connection to database is already open...   (163 Views)
ok im trying to connect to a database and then update it from a datagrid. when i start debugging i instantly get an error telling me that the connection is already open, so if i take the code out where i am opening the connection it gives me an error saying connection is closed, lol. i have highlighted in yellow where the error is comming up. please help Code: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Configuration; namespace Database { /// /// Summary description for WebForm1. /// public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.Button Button1; protected System.Web.UI.WebControls.Button Button2; protected System.Web.UI.WebControls.RadioButton RadioButton1; protected System.Web.UI.WebControls.RadioButton RadioButton2; protected System.Web.UI.WebControls.Label lblName; protected System.Web.UI.WebControls.TextBox TextBox2; protected System.Web.UI.WebControls.Button btnProcess; protected System.Web.UI.WebControls.TextBox TextBox1; protected System.Web.UI.WebControls.Button btnAddNew; protected System.Web.UI.WebControls.DataGrid DataGrid1; protected System.Web.UI.WebControls.Label Label2; protected System.Web.UI.WebControls.Label lblTitle; private SqlConnection myConnection; private void Page_Load(object sender, System.EventArgs e) { myConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"].ToString()); if(!Page.IsPostBack) { BindData(); } } override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.DataGrid1.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_CancelCommand_1); this.DataGrid1.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_EditCommand_1); this.DataGrid1.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_UpdateCommand_1); this.DataGrid1.SelectedIndexChanged += new System.EventHandler(this.DataGrid1_SelectedIndexChanged); this.Load += new System.EventHandler(this.Page_Load); } private void DataGrid1_EditCommand_1(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { // We use CommandEventArgs e to get the row which is being clicked // This also changes the DataGrid labels into Textboxes so user can edit them DataGrid1.EditItemIndex = e.Item.ItemIndex; // Always bind the data so the datagrid can be displayed. BindData(); } private void DataGrid1_UpdateCommand_1(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { System.Web.UI.WebControls.TextBox cName = new System.Web.UI.WebControls.TextBox(); cName = (System.Web.UI.WebControls.TextBox) e.Item.Cells[1].Controls[0]; SqlCommand myCommand = new SqlCommand("SP_UpdatePerson",myConnection); myCommand.CommandType = CommandType.StoredProcedure; myCommand.Parameters.Add(new SqlParameter("@PersonName",SqlDbType.NVarChar,50)); myCommand.Parameters["@PersonName"].Value = cName.Text; myConnection.Open(); myCommand.ExecuteNonQuery(); myConnection.Close(); DataGrid1.EditItemIndex = -1; BindData(); } private void DataGrid1_CancelCommand_1(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { // we do in the cancel method is to assign '-1' to the datagrid editItemIndex // Once the edititemindex is set to '-1' the datagrid returns back to its original condition DataGrid1.EditItemIndex = -1; BindData(); } private void BindData() { SqlCommand myCommand = new SqlCommand("SP_SELECT_Customers",myConnection); myCommand.CommandType = CommandType.StoredProcedure; SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand); DataSet ds = new DataSet(); myAdapter.Fill(ds, "Customers"); myConnection.Open(); myCommand.ExecuteNonQuery(); DataGrid1.DataSource = ds; BindData(); myConnection.Close(); } private void DataGrid1_SelectedIndexChanged(object sender, System.EventArgs e) { // prints the value of the first cell in the DataGrid Label2.Text += DataGrid1.SelectedItem.Cells[0].Text; } } }
Accessing Controls on a different form from one form.   (148 Views)
Pretty much as it says. I tried through every little Form1.(names).blah.blah But I could not find how to access a listbox on Form2 from form1. Please help. Tim, Originally Posted by nvoigt Thats about as contra-OOP as it gets. If you need to set something in Form2 from an instance of Form1, write a method or property in Form2 that takes the text as parameter and then sets it's own textbox. Call this method on your instance of Form2. Correct. This really is the best simple way of doing things, and its the method I use 90% of the time. The parent (creating) form should set properties on the child form, and the child form should fire events that the parent is interested in knowing if something happens. So for instance, as nvoigt said, if you are in MainForm, and you wish to set a textbox on Form2, Form2 really should have a property like this: Code: public class Form2 : Form { [...Form2's Code...] public string TheText { get { return textBox1.Text; } set { textBox1.Text = value; } } [...The rest of Form2's Code...] } If Form2 has a button and MainForm wants to know when that button is clicked, Form2 should have an event: Code: public class Form2 : Form { [...Form2's Code...] public event EventHandler ButtonClicked; // called in Form2 when the button is clicked void button1_Click(object sender, EventArgs e) { // Tell our listeners, in this case MainForm, the button was clicked if (ButtonClicked != null) { ButtonClicked(this, EventArgs.Empty); } } [...The rest of Form2's Code...] } This has the added advantage of allowing multiple forms know when the button is clicked. In MainForm, this is how you could use these new properties of Form2: Code: public class MainForm() { [...MainForm's Code...] void CreateNewForm2() { Form2 form2 = new Form2(); form2.TheText = "G'day world!"; // add a new event handler form2.ButtonClicked += new EventHandler(Form2_ButtonClicked); } // We then have the event handler: void Form2_ButtonClicked(object sender, EventArgs e) { MessageBox.Show("OMG! The button in Form2 was clicked, but I'm showing you this from MainForm!!!!1"); } [...The rest of MainForm's Code...] }
Re: How To : User Control   (158 Views)
Hi all I've created a user control that contains 3 buttons Add / Modify / Delete. The click events of the controls are calling abstract methods. I'm placing the control on a form, form1.cs file, i would like to call a specific method for the click of the add button of the control. Can anybody help me on accomplishing this
Using new/overrides etc methods? im a bit in a worry   (124 Views)
I am designing a plugin system by my own to meet my needs. There is the "interface" for all plugins that is like this: Code: public abstract class IrcPluginBase { private IrcClient _parent; public IrcClient Parent { get { return _parent; } set { _parent = value; } } public void SetParent(IrcClient parent) { _parent = parent; } public virtual void RawCommandReceived(string command) {} public void SendRawCommand(string command) { _parent.SocketRef.Send(command); } public void SendText(string nick, string channel, string txt) { } } then here is a plugin's 'RawCommandReceived' function: Code: public void RawCommandReceived(string command) { MessageBox.Show("hey"); } } My main class should then do this: Code: foreach (IrcPluginBase plugin in _plugins) { plugin.RawCommandReceived(msg); } The problem is that this last line is calling the abstract class' 'RawCommandReceived' and not the plugin's overrided one How should I go around this I also tried removing the virtual/override keywords and put "new" but still the same problem
A problem with graphics   (145 Views)
Hi all I have been playing around with some basic graphic elements to get in touch with OOP and C#. i have managed to put the following piece of code together but am experiencing an unusual issue with it. Code: 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 Graphictest1 { public partial class Form1 : Form { public int xpos = 10; public int ypos = 10; Bitmap myBitmap = new Bitmap(@"c:\green_ball.bmp"); //64 x 64 pixel images Bitmap myBitmap1 = new Bitmap(@"c:\wall1.bmp"); Bitmap myBitmap2 = new Bitmap(@"c:\brown_ball.bmp"); public Graphics g; private Bitmap myscreen; public Form1() { InitializeComponent(); this.SetStyle(ControlStyles.PaintingInWmPaint, true); this.SetStyle(ControlStyles.UserPaint, true); this.SetStyle(ControlStyles.DoubleBuffer, true); this.UpdateStyles(); myscreen = draw(); this.Invalidate(); } public Bitmap draw() { Bitmap back = new Bitmap(this.Width, this.Height); Graphics p = Graphics.FromImage(back); int x; int y; int tile = 1; myBitmap.MakeTransparent(Color.White); myBitmap1.MakeTransparent(Color.White); myBitmap2.MakeTransparent(Color.White); for (y = 0; y
accessibilty between 2 forms   (153 Views)
Hi: If I created two forms in 1 solution, and I insert 1 button in Form1, how could I access this button in Form2 Thanx, yea,I got it, thanx
What is equal to Dim in C#?   (143 Views)
whats eqaul to dim in C#
Why haven't C# a inputbox?   (155 Views)
Hi. I did thought that C# has a inputbox like do. But no, but yes. I've seen some coders who have created a inputbox in C# but they have been using too. I wonder what is the "inputbox" command in c# Is is like InputBox.Show(". What is your name", OK, Cancle) , And they did make one, and it lives in the VisualBasic namespace. You can use it directly in your C# what's the flaw It's there, and it's usable. It's not part of the language or the CLR, just the Framework. On the other hand, how many good programs have you used that get input this way Really, I'm betting it's fairly few. That's because a custom form can be so much more, well, custom-built to the situation.
Problem with code trying to count number of words etc, in asked String   (158 Views)
I am trying to find the Number of words, Upper/Lowercase Letters and number of SPACES in a Entered string. The output shows that there is 0 Words,Upper/Lowercase Letters, or Spaces. using System; using System.IO; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("Enter a String"); Console.ReadLine(); char ch; int x; int space = 0; int Lowercase = 0; int Uppercase = 0; int words = 0; do { x = Console.Read(); ch = Convert.ToChar(x); if (ch.Equals(' ')) { space++; } else if (Char.IsLower(ch)) { Lowercase++; } else if (Char.IsUpper(ch)) { Uppercase++; } if (ch.Equals(x)) { words++; } } while (ch != '\r'); Console.WriteLine(); Console.WriteLine("# of spaces: {0}", space); Console.WriteLine("# of Lowercase Letters: {0}", Lowercase); Console.WriteLine("# of Uppercase Letters: {0}", Uppercase); Console.WriteLine("# of Words: {0}", words); Console.ReadLine(); Console.ReadLine(); } } }
Calling a Void That Edits a TextBox From Another Class   (134 Views)
I know this has been asked millions of times and I apologize, I have been looking for a week and can't find a viable solution. Basically I have a TextBox in my main form and in that forms code I have a void called write which outputs to the TextBox. I am trying to figure out how I can call this void from any class in my program. Here is an example. public partial class frmMain : Form { public frmMain() { InitializeComponent(); } private void frmMain_Load(object sender, EventArgs e) { RichTextBoxWordWrap.Test(rtbConsole); Write("Console", "Welcome!"); } //This is the void I need to call, I can't make it static because of the TextBox.. public void Write(string User, string Text) { rtbConsole.SelectionColor = Color.Black; rtbConsole.SelectedText = "Test"; } } public partial class frmSettings : Form { public frmSettings() { InitializeComponent(); } //This is how I would like to be able to call it in any class. private void frmSettings_Load(object sender, EventArgs e) { frmMain.Write("Settings", "Saved"); } } , JackOfTrades, on 24 August 2012 - 03:11 PM, said:You're doing it wrong., We've already told you that's the wrong approach. Read the links we've provided to learn how to do it right. , It's because you're creating a new instance of the class in both forms. A class is like a blueprint, instances are the things built from the blueprint. new does the building. You've created two copies of the same thing, then modified one. The second won't reflect the changes to the first. There are a few ways to handle this. If Form1 is the one that creates Form2, you could change Form2 to have a constructor parameter to pass the instance of your ConsoleText class from the first to the second. Or, you could read up on the Singleton pattern, and change your ConsoleText class so that there is only ever one instance, and that instance is available statically from the class itself. Static properties/methods/fields are shared across all instances of a class. If you're going to have lots of forms all subscribing to the same event triggered from a single form, the Singleton may be the way to go. If you just want one form to listen to the other, it might be smarter (or at least simpler) to pass the reference to Form2.
Dynamic asp component with asp children   (147 Views)
, I am stuck with this problem here. I would like to reproduce several orderlines to represent the items that are currently in a basket I had imagined that I would have a structure like this Product Name Price At first I used a literal and put all the information above in a dynamic way. The problem arises when I need to check the input text. I have to check to see if there is a number in it, and then I need to retrieve that value to update the basket. It appears that literals cannot have children controls. So I managed to add dynamic literals and dynamic textboxes and managed to have them one near the other. This solutions however isn't satisfactory because i am quite limited in placing the object in the right. For example, I have to put the input text immediately on the left of the price (but this is inside the literal). It is difficult to place objects also because all my measures are in % , and also impossible to use absolute positioning because all these boxes and literals are in the same big container. I would like to have a different container for every literal and his textbox. In the end the question is: is there an asp object that allows asp children I would create one div, place an asp image inside, some asp labels and the asp textbox. is it impossible
get text from handle window   (164 Views)
Hi I handle a window by this code line: child = FindWindowEx(Parent, IntPtr.Zero, "DirectUIHWND"); This window is belong to "DirectUIHWND" class and he have textBox. Im trying to get this text from textBox. I've tryed the next function: int winText = GetWindowText((int)child, strBldr, strBldr.Capacity); But this function return the capture text and not the text from the searchBox. Any idea how can i get the text from the handle window
Unit test private method throwing event   (154 Views)
I have a class that contains a private method that under certain parameters will throw an event. For example: class c { public event EventHandler Event1; private void MethodToTest(String s) { if(s.Equals("test") if(Event1 != null) Event1(); } } Then in my unit test class I have the test that tries: [TestMethod()] public void Test1() { c_Accessor accessor = new c_Accessor(); //Tests the tick Command accessor.MethodToTest("test"); e4.WaitOne(); Assert.IsTrue(true); } where e4.Set() is called in the event associated with Event1. So my questions are, How do I associate the event with the accessor. it provides the method accessor.add_Event1() but I'm not sure how to use that. or, if that isn't the correct way to do this what would be the best way without testing the implementation
How to open emails in webbrowser?   (182 Views)
Is it possible to open emails in webbrowser I tried doing a foreach statement but it dosnt click the link. , We're not playing this game again, kytro360. Post the code you've tried, and the exact exception text, or exactly what happens, and exactly what you want to happen, or this post is getting moved to the bin. You have a habit of being very sparse on details. To else: I've already said it. We don't need 10 other people jumping on it. Once is enough.
Looking for good book suggestions   (172 Views)
I am a book learner. I like books over tutorials or class rooms because I can go back and re-read until I understand what it says. Does anyone have any recomendations for good books to get started in and advance in C# My goal is to become proficient with C# then move into SQL Server. I am using VS 2008 Standard for an IDE. I know there are a couple of technologies that can be used when I get to that point for linking the two, so any advise as to the benefits of either would also be appreciated. That will help to point me in the right direction in my studies. , We don't need two threads about this when another is stickied. Closed.
XmlSerializer problem   (156 Views)
. Whenever i serialize data using XmlSerializer, for some reason the xml that is created gets an extra ">" character in it. SDSD SDSD SDSD 1 3 1 0 10 0 > The closing tag gets an extra ">" for some reason. If i remove it, the code works but if i don't it just gives an error(that points out to that exact location). What can cause that
Searching a Sorted Ascending Array   (149 Views)
Hi. I have a bit of a problem. Suppose a set of names (say Countries) are held in ascending alphabetical order in the array. Using C Sharp of course how would I search for a given country name which is held in a variable, taking advantage of the array ordering. Also, what would be the best way to a new country name to this array String[] countries = { "Britain", "France", "Germany", "Italy", "Peru", "Uruguay" }; String searchValue = "Germany"; int counter = 0; int noOfCountries = countries.Length; // add new country String newCountry = "China"; Array.Resize(ref countries, 4); countries[3] = newCountry; Console.WriteLine("The Array content after change\n");
Depth first search early stages - beginners problem   (156 Views)
, I'm trying an attempt at a very primitive depth first search algorithm andI seem to be stuck quite early on, on some simple logic. Here is my code: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Search { class Node { public Node[] Connections; public string name; public Node(string Name) { name = Name; //Connections = null; } } class Sort { public static Node[] root; int max = 7; public void DFS(Node start, string end) { Node A = new Node("A"); Node B = new Node("B"); Node C = new Node("C"); Node D = new Node("D"); Node E = new Node("E"); Node F = new Node("F"); Node G = new Node("G"); A.Connections = new Node[3]; A.Connections[0] = A; A.Connections[1] = B; A.Connections[2] = C; B.Connections = new Node[3]; B.Connections[0] = B; B.Connections[1] = D; B.Connections[2] = E; C.Connections = new Node[3]; C.Connections[0] = C; C.Connections[1] = F; C.Connections[2] = G; root = new Node[7]; root[0] = A; root[1] = B; root[2] = C; root[3] = D; root[4] = E; root[5] = F; root[6] = G; for (int i = 0; i < max; i++) { if (start.Connections[i].name.CompareTo(end) != 0) { Console.WriteLine("Count " + i); } else Console.WriteLine("Found: " + end + " after " + i + " counts"); } } } } and here is the code to run the program: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Search { class Program { static void Main(string[] args) { Sort Run = new Sort(); Run.DFS(Sort.root[0], "C"); Console.Read(); } } } I'm not sure if my problem is coming from the way I call Sort.root[0] or something else entirely. Even if the code isn't complete it should still output something. It runs with no errors but gets caught in an infinite loop. Can anyone help me out Thank you
Object referance not set to an instance of an object ERROR   (153 Views)
I have a program which 4 different files. The file to actually run and test all of my methods works perfectly for the integer array but not for the string array. Can someone please help me with the error When I run the program, the integer array list prints out, the max, min, remove methods all work. Then the string array prints but none of the methods print until I press enter, which brings up the error message. However, when I press enter, it does print the min, max, and remove method. HERE IS WHAT I FIRST GET WHEN I RUN THE PROGRAM: The original list: 5 12 2 29 5 2 33 -4 111 4 17 Maximum value: 111 Minimum value: -4 Remove element from position 2: 5 17 2 29 5 2 33 -4 111 4 Remove the first element: 4 17 2 29 5 2 33 -4 111 Insertion sort: 111 33 29 17 17 5 4 4 2 String array: b a f d c e WHEN I PRESS ENTER: String array: b a f d c e Maximum value: f Minimum value: a Remove element from position 2: b f d c e static void Main(string[] args) { UnorderedArrayList u = new UnorderedArrayList (); int var = 5; u.insert(ref var); var = 12; u.insert(ref var); var = 2; u.insert(ref var); var = 29; u.insert(ref var); var = 5; u.insert(ref var); var = 2; u.insert(ref var); var = 33; u.insert(ref var); var = -4; u.insert(ref var); var = 111; u.insert(ref var); var = 4; u.insert(ref var); var = 17; u.insert(ref var); Console.WriteLine("The original list:"); u.print(); Console.WriteLine(); Console.WriteLine("Maximum value:"); Console.WriteLine(u.max()); Console.WriteLine(); Console.WriteLine("Minimum value:"); Console.WriteLine(u.min()); Console.WriteLine(); Console.WriteLine("Remove element from position 2:"); u.remove(2); u.print(); Console.WriteLine(); Console.WriteLine("Remove the first element:"); u.removeFirst(5); u.print(); Console.WriteLine(); Console.WriteLine("Insertion sort:"); u.InsertionSort(); u.print(); Console.WriteLine(); UnorderedArrayList x = new UnorderedArrayList(); Console.WriteLine("String array:"); string svar = "b"; x.insert(ref svar); svar = "a"; x.insert(ref svar); svar = "f"; x.insert(ref svar); svar = "d"; x.insert(ref svar); svar = "c"; x.insert(ref svar); svar = "e"; x.insert(ref svar); x.print(); Console.ReadLine(); Console.WriteLine("Maximum value:"); Console.WriteLine(x.max()); Console.WriteLine(); Console.WriteLine("Minimum value:"); Console.WriteLine(x.min()); Console.WriteLine(); Console.WriteLine("Remove element from position 2:"); x.remove("f"); x.print(); Console.WriteLine(); Console.WriteLine("Insertion sort:"); x.InsertionSort(); x.print(); Console.WriteLine(); } public int CompareTo(object obj) { throw new NotImplementedException(); } } }
AVI Recording   (143 Views)
Hi Everybody, I need to write a piece of software that creates an AVI from the bunch of images. I've been googling this but the I haven't found a clear way to proceed. Which library is recommended for this I've bumped to avifil32.dll but I am wondering if this is a legacy dll which perhaps should not be used Or should I look more into DirectShow (quartz.dll) or which is the state-of-art for creating video files
Adding elements to a set and printing an array copy?   (176 Views)
all...I've been a lurker on this site for quite some time but I've reached the point where I had to post a question. I'm working w/ the generic interface ISet. I've created a class (Set) that inherits from interface ISet. I'm trying to figure out how I would go about adding elements to a set. Also, I'm trying to figure out how to use the ToArray() method to print out an array of the set. I've been at this for a few hours and haven't made much progress, unfortunately. Can someone point me in the right direction This is what I have so you can see...not a whole lot. There are other methods/definitions but I figure if I can figure out add & ToArray(), I'll be able to tackle the rest. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Inter { public interface ISet { void Add(T element); // T Remove(T element); // bool Contains(T element); // ISet Intersect(ISet otherset); // ISet Union(ISet otherset); T[] ToArray(); } class Set : ISet { public void Add(T element) { //not sure about the logic } // T Remove(T element); // bool Contains(T element) // ISet Intersect(ISet otherset); // ISet Union(ISet otherset); public T[] ToArray() { //not sure about the logic T[] arr = new T[0]; return arr; } } class Program { static void Main(string[] args) { var someObj = new Set(); someObj.Add(5); Console.ReadLine(); } } } , I realize that this isn't the point, but please: QuoteLet's say you choose to use an ArrayList.
Formatting a given number of words into lines of size "x"   (132 Views)
I have a problem for a project of mine, firstly I'd like to tell you what the project is: I basically have to format a large amount of text based on a specific command done through command line upon program startMy program will then read the entire file (full of words) and split them based on whitespacesNow that an array holds the split strings, as a parameter passed in before program execution, the user has to specify how many words he would like in a lineSo all I do next is create a list of lines (lines are instances of classes which hold an array of size line length)Every so many words, for example 21, add a new line to line list, this part isn't the problemThe problem I'm having is trying to get the remaining words in the array and create a new line for them as they are the last words in the array, but how do I go about doing this e.g. 86 words in array, 4 lines of size 21 have been created, but the remaining 4 words do not get put in a new line. Many thanks This post has been edited by MitchellT: 20 March 2012 - 10:59 AM , Fixed it. private static void Fill() { int wordCount = 0; for (int i = 0; i
Jumble Game modifications   (156 Views)
I have to create a game where a random array of letters is displayed and the user is prompted to guess what the letters spell out. After that it is supposed to re-jumble the next set of letters and have them guess again. By the error message I got I think i'm missing a big part of this but I'm not sure what it is... class Jumble { //data members string[] arywords = { "TABLE", "CHAIR", "PLACEMAT", "PLATE", "FORK", "KNIFE" }; string word; char[] displayWord; //constructor public Jumble() { GenerateWord(); } public string HiddenWord { get { return word; } } //methods public string DisplayScramble() { string returnvalue = null; for (int i = 0; i < displayWord.Length; i++) returnvalue = returnvalue + displayWord[i]; return returnvalue; } public void ScrambleWord() { int random; char temp; Random randObj = new Random(); displayWord = new char[word.Length]; //initializing array for (int i = 0; i < word.Length; i++) { do random = randObj.Next(word.Length); while (displayWord[random] != 0); temp = word[i]; displayWord[random] = temp; } } private void GenerateWord() { int number; Random generator = new Random(); number = generator.Next(arywords.Length); word = arywords[number]; } public bool CompareGuess(string guess) { bool value; if (guess == word) value = true; else value = false; return value; } } } This post has been edited by Atli: 03 February 2012 - 11:09 PM Reason for edit:: Added [code] tags.
Chess Game [need some guidance]   (178 Views)
hay,i need to make a chess game. i need some advice on a good approch for this. i tryed to make an abstrac call called Piece and then just use him in diffrent class's like Knight,Queen but im not sure, for some reson it dosnt feel right. 1.i was thinking mybee to creat 8 user controls for the pieces, so it will easy to use the mouse events for each piece.(i think i will try to do a drag and drop game) 2.create a User Control to the table him self. this is all i got for now, im not sure in what way to approch this . i need advice. *(i realy dont mind if it will take me a lot of time becouse i think i will learn a lot from this) *(sorry for my english) *
RS232 communication - random data sent after some time   (154 Views)
, I'm trying to send some data to serial port. I'm using Aten UC-232A USB to serial adapter and I've installed the supplied drivers for Win7 x64. I haven't found anyone who has had any similar problems with it. The other side of serial cable is connected to another laptop which has a serial port and I'm receiving data in Linux console. I believe the port is configured correctly on both sides (speed 9600, 8 data bits, 1 stop bit, no parity, no flow control). I've tried some code examples and they all work fine, except: Sometimes, data is sent correctly, for example, I'm sending characters ABCDEFGH. But usually, they get corrupted, like ACBDEGH, AC CHEF etc. ...then, after some time, some random is data starts flowing! Mostly unknown characters and the flow doesn't stop. I've no idea what is happening - I don't know if this is a programming error (most probably not) or is there a problem with my USB-to-serial adapter or my system.. I could go buy another adapter with a different chipset (the FTDI one, not Prolific like this one). I have no idea what initiates that random flow of data. It happens randomly - sometimes not at all, sometimes almost instantly after I open the port.
problem with splitting and updating sql query   (165 Views)
I am working on this site and i need to read data from my database and in the city names i need to update and make sure that the second name in the cities is capitalized, instead of going through 29,000 by hand i wanted to do it by code. here is what i have so far, can someone give me a hint or help me figure out how to do this. protected String getUpdatedCity() { SqlConnection connection = new SqlConnection(); SqlCommand command = new SqlCommand(); try { connection = new SqlConnection(ConfigurationManager.ConnectionStrings["BuyersListingConnectionString"].ConnectionString); connection.Open(); String sqlCommand = "SELECT City.CityName, City.CityID, State.StateName" + "FROM City, State" + "WHERE City.StateID = State.StateID"; command = new SqlCommand(sqlCommand, connection); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { return reader[0].ToString(); } command.Dispose(); connection.Close(); } catch (Exception ex) { String s = "Error: " + ex; if (connection != null) { command.Dispose(); connection.Close(); } } return ""; } This post has been edited by JackOfTrades: 17 November 2011 - 02:29 PM Reason for edit:: Added code tags
A query in implementing Point of Sale application.   (144 Views)
Acutally, I am developing an application of Point of Sale and I am stuck in one place where I've an Entity named "PurchaseOrderDetail" which is used for storing all the Purchase related items and as soon as Client submit the information a receipt is generated and will update the Stocks. But I want your suggestion in a way is it correct to update the Stock since He first needs to get the stocks from the Dealer and it might be possible that the Dealer don't have some items at that moment. But here the Stock is getting updated already, so how can I make all these things to get synchronized. Any kind of suggestions would be greatly appreciated, do tell me if my logic is leading me wrong. This post has been edited by Martyr2: 30 May 2011 - 10:13 PM Reason for edit:: Removed unncessary formatting.
Image names   (154 Views)
Hi Guys, sorry for the weird topic name But wasn't sure on what name to come up with. Basically I am having issues with naming my images that I download from a list of URLs. The images are downloaded using WebClient function and then sorted into various folder names which again is created by my code. For example: Folder SP1 will contain a large and thumb folder and images inside them. and folder SP2 will also contain a large and thumb folder. Once each image is downloaded it is renamed in numeric order like 1.jpg, 2.jpg and 3.jpg. depending upon the order of the images downloaded. Inside each folder the image names will start from 1.jpg, 2.jpg etc.... Now the issue I am having is that I am not able to reset the number once new images are downloaded into a new folder for example if SP1 have images from 1.jpg to 10.jpg then SP2 will have image names starting from 11.jpg to 20jpg Not able to figure out this Here is my code: WebClient wc = new WebClient(); foreach (Images Img in ImgList) { string PropIdFolder = "SP" + pList.FirstOrDefault(x => x.Prop_VebraID == Img.Prop_VebraID).Prop_ID; string LargeFolder = "large"; string ThumbFolder = "thumb"; //Get extension of the file string ext = Path.GetExtension(Img.File_url); string URL = Img.File_url; //Replace the existing url with the new url string newURL = URL.Replace("", ""); //thumb Directory thumbDir = Path.Combine(ImagePath, PropIdFolder, ThumbFolder); if (!System.IO.Directory.Exists(thumbDir)) { System.IO.Directory.CreateDirectory(thumbDir); } //Large Directory largeDir = Path.Combine(ImagePath, PropIdFolder, LargeFolder); if (!System.IO.Directory.Exists(largeDir)) { System.IO.Directory.CreateDirectory(largeDir); } int idx = 0; if (ext == ".jpg" || ext == ".png" || ext == ".gif" || ext == ".jpeg") { try { idx++; string[] split = newURL.Split('.'); string[] split2 = Img.File_url.Split('.'); //Download files into subfolders wc.DownloadFile(newURL, largeDir + "\\" + idx.ToString() + "." + split[split.Length - 1]); wc.DownloadFile(Img.File_url, thumbDir + "\\" + idx.ToString() + "." + split2[split.Length - 1]); } catch (Exception ex) { _log.WriteException(ex, string.Format("Downloading large for property {0}", pList.FirstOrDefault(x => x.Prop_VebraID == Img.Prop_VebraID).Prop_ID)); } } }
C# Cafe Windows Form - Clear Order total   (143 Views)
I have some code not working properly for me. private void menuClearOrder_Click(object sender, EventArgs e) { this.listBoxEntree.ClearSelected(); this.menuEntree2.ClearSelected(); this.comboBox2.SelectedIndex = -1; this.comboBox2.Text = " "; newOrder.Entree = " "; newOrder.Entree2 = " "; newOrder.ExtrasSelection = " "; comboBox2.Visible = false; label2.Visible = false; newOrder.DetermineTotalCharges().ToString(""); } Everything is working right except for clearing the Total Charges. The listBox is cleared, the comboBox is cleared, and it is made invisible. However, when I place a new order, that total is added onto the previous total. I can't figure out how to clear the total charges when I clear my order.
I have a 2 table in my database. Lets call it tblStudents and tblCourse. In my tblStudents I have field names with StudentID, StudentName, StudentGender, and at my tblCourse I have StudentID, StudentCourse, StudentYear and StudentNumber. I have a windows form which is I need to display all info of a certain student. this is working perfectly strSelect2 = ("select * from tblStudents where StudentID = @id"); but, I need to display the course and year of a certain student too. The problem is I don't know how to select multiple tables.
c# Index was outside the bounds of the array.   (189 Views)
I have an application where you have a multiline textbox. when you click calculate the application will find the average of all the even and odd numbers you typed in there. I did the code using a do while loop. My assignment is due tomorrow and i need help quick! i get an "Index was outside the bounds of the array." error when i play it. heres the code: there error starts at "while ((textBox1.Lines[index] != null) && (textBox1.Lines[index] != "")) private void button1_Click(object sender, EventArgs e) { double num = 0.0; double num2 = 0.0; int index = 0; string str = ""; int num4 = 0; int num5 = 0; while ((textBox1.Lines[index] != null) && (textBox1.Lines[index] != "")) { str = textBox1.Lines[index]; int num6 = Convert.ToInt16(str); if (IsEven(num6)) { num = (num * num5) + num6; num /= (double)(num5 + 1); num5++; } else { num2 = (num2 * num4) + num6; num2 /= (double)(num4 + 1); num4++; } index++; } label1.Text = Convert.ToString(num); label2.Text = Convert.ToString(num2); } public static bool IsEven(int value) { return ((value % 2) == 0); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); }
Problem in dynamically creating picture boxes!   (171 Views)
I am trying to implement a program that displays multiple picture boxes dynamically. This code does not give any error but display only one picture box. I am unable to find the problem in it. I am unable to find the problem. It is a part of my assignment which, I have to submit in 2 days. Kindly help me. 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 WindowsFormsApplication1 { public partial class Form1 : Form { int num; public Form1() { InitializeComponent(); num = 10; } private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { PictureBox[] pb = new PictureBox[num]; for (int i = 0; i
Functions   (140 Views)
, I'm a beginner to C# and im following some tutorials from various sites. I'm just learning about Functions and i understand what they are used for. (It shortens code etc) but the tutorial doesn't show they are used in a program. I'm sat here trying to use them in a program but i can't get it to work! The site im using is: And what i have tried is: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _World { class Program { static void Main(string[] args) { int result = AddNumbers(10, 5); Console.WriteLine(result); } public int AddNumbers (int number1, int number2) { int result = number1 + number2; return result; } } } , Definitely do what modi says, but I can already see the issue here. The problem is that the Main method is static. It has to be. If you haven't gotten to classes yet, you probably don't know what static means. Suffice it to say that static can't talk to non-static. So if you're using a Console Application, for the moment, just mark your methods static.
C# and clipboard   (267 Views)
I have a form that has five textbox and a submit button, I would like to click the submit button and populate the five textboxes with objects from clipboard, I know the first action will populate the textbox with the first object but a little lost on how to proceed from there, I am a novice person and wanted to use C# for the action instead of copying and pasting private void button1_Click(object sender, EventArgs e) { IDataObject idata = Clipboard.GetDataObject(); textBox1.Text = (String)idata.GetData(DataFormats.Text); } I believe I am on the right track and probably need an array that would count the number of objects in the clipboard then would cycle down each one but if one textbox is not null would go to the next , the problem would be when the first object is populated it should be cleared before the next one is proceeded, I have an idea I am on the right track but like I said not exactly sure how to approach this Can someone give me some pointers and no this is not homework just want to learn how to do this slowly.
check if icon was pressed   (140 Views)
How can i check if someone pressed on certain icon like internet explorer i thought about check where is the mouse position and check it but it isn't the same position in all of the computer , I'm not giving the benefit of the doubt. He's already had one thread closed for potential malicious activity: http://www.dreaminco...r-computer-c%23 Thread closed. Do not open any more threads that involve the potential for spyware or malware uses, or you may have your posting privileges revoked.
How can I implement a rating system providing multiple users to vote ?   (154 Views)
I want to implement a rating system for my website, where my clients can rate suppliers. The scenario is like there will be a series of questions with rating from 1 - 5. Each supplier will be rated according to some series of questions. As shown below. I tried to create a simple rating control for one question and the my calculation was Sum. Of Ratings / No of users. Like, For a question Q1, User1 gave 1 rating User2 gave 1 rating User3 gave 3 rating User4 gave 3 rating User5 gave 2 rating So the avg. rating for the question is = (1 + 1 + 3 + 3 + 2) / (5) = 10/5 = 2 star rating by 5 users similarly, If I get ratings 3 star by 6 users for Q2 If I get ratings 4 star by 6 users for Q3 If I get ratings 2 star by 6 users for Q4 Correct me if the above calculation is wrong. And if it is correct then what should be the calculation for finding the avg. rating of the overall questions of any supplier There can be many question, each question can be rated by multiple users. I googled up but ended up here.
I am having an issue getting my desired outcome.   (162 Views)
Basically, I am trying to check and see if a player types in a cretin command such as "!help" it will write some text to the console. I could use help with Syntax..and even I am not sure my method is the easiest/best. Here is what I have: class Commands { public void cmd() { string help = "!help"; string attack = "!attack"; string equipment = "!equipment"; string clothing = "!clothing"; string estates = "!estates"; string location = "!location"; string work = "!work"; string train = "!train"; string go = "!go"; string track = "!track"; string powers = "!powers"; string money = "!money"; string stats = "!stats"; string skills = "!skills"; string eat = "!eat"; string armor = "!armor"; string north = "!north"; string south = "!south"; string east = "!east"; string west = "!west"; string yes = "!yes"; string no = "!no"; for (; ; ) { // statements string holdValue = ""; if (Console.ReadLine() == "!help") { Console.WriteLine(help); } if (Console.ReadLine() == "!attack") { Console.WriteLine("You are Attacking!"); } } } Then in my main I have this: static void Main(string[] args) { Commands commands = new Commands(); commands.cmd(); } the problem is sometimes when I type in !attack it will say you are attacking and sometimes it wont..not sure why I am getting this outcome. If anyone is curious..its just a lil Mini mud game.
LINQ to Entities: Pass a value to fn to update table value.   (143 Views)
I'm attempting to update a table entry based on the input of a user. The user is presented with a series of labels which are actually styled radio buttons. The labels correspond with an item in the table. Once the user makes a selection it is saved to the table. I am trying to create a function that allows the user to change their selection. //passes the new selection ID to the makeChange function. public ActionResult makeChange(string ID) { Entities new = (from X in new.SelectionChoices where new.ID == ID select new).First(); new.SelectionChoices = ID; new.SaveChanges(); } I'm not sure if I'm headed in the correct direction or not.
Assigning values from a cell to a cell datagridview   (143 Views)
int rowsCount = 0; //This checks to see that both textbox for items and subitems do not gain focus at the same time if (textBoxSubItems.Text != string.Empty) txtItems.Enabled = false; else txtItems.Enabled = true; if (comboBoxItems.SelectedItem != null) { int idx = dataGridViewTimesheet.Rows.Add(); DataGridViewRow row = dataGridViewTimesheet.Rows[idx]; row.Cells["items"].Value = comboBoxItems.SelectedItem.ToString() + "-" + textBoxSubItems.Text; row.Cells["fromTime"].Value = DateTime.Now.ToLongTimeString(); row.Cells["toTime"].Value = null; row.Cells["duration"].Value = null; row.Cells["subTotal"].Value = null; // row.Cells["comments"].Value = "1"; } else MessageBox.Show("Please select an item"); string strGetColumnValue; if (dataGridViewTimesheet.Rows.Count != 0) rowsCount = dataGridViewTimesheet.Rows.Count; else MessageBox.Show("No row in the datagridview"); while(dataGridViewTimesheet.Rows.Count>0) try{ if (dataGridViewTimesheet.CurrentRow != null) for (int counter = 0; counter < dataGridViewTimesheet.Columns.Count; counter++) { if (dataGridViewTimesheet.Columns[counter].Index == 3) { strGetColumnValue = dataGridViewTimesheet.Rows[rowsCount].Cells[counter].Value.ToString(); dataGridViewTimesheet.Rows[rowsCount - 1].Cells[3].Value = strGetColumnValue; } } } catch(Exception ex){ MessageBox.Show(ex.ToString()); } Please i have 6 columns in a datagridview, the rows are added dynamically. What i want is when rows are more than one in the datagridview it should assign the value of the second column on the current(the last row created) row to the third column of the previous row. How do I achieve this.
Maximum number of calls to a function in a timespan   (169 Views)
I was wondering how one would go about enforcing a maximum of calls to a function within a specific timespan. specifically, this involves Web Service API Rate Limits. my idea was: use a dictionary with the key being the unix timestamp, and the value being the number of calls made in that second. if no calls were made at a specific timestamp, then no key would be created for it. everytime i called the function, i would take the current time, subtract 10 minutes* from it, then trim any timestamps that were OLDER that value. i would then check that if i hit my rate limit or not and block if it wasn't safe to call the api. *10 minutes is significant number because that is the timespan for the api. my question is: is this solution acceptable It seems like their should be a better way of doing this(no, i DO NOT have a way to ask the API for my remaining api calls) - preferably a solution already on .NET. please don't recommend i try to reduce the number of API calls - the operation i'm attempting to implement requires a rather significant number of calls and i have already optimized it considerably. please don't recommend i try harder to use fewer calls.
Xml error?!   (153 Views)
system.xml.serialization.xmlserializer is defined in an assembly that isnot referenced you must add a reference to assembly 'system.Xml,version=,culture=....,publicKeyToken=........' i can't understand it and after search i got nothing .
Printing All Content of List   (153 Views)
i have created a menu driven application where the user is asked to add either a book, dvd, or a cd(options 1,2,3) to a product list. The details they enter (author, publisher, price) etc are added to the product list. Option 4 of the menu is Show Product details, where all the details of the products entered by the user are displayed. i need is the details of the products in the list to be displayed. Having not worked with lists very often i am unsure how to achieve this. I have created a Show() method where the code to display the list is to be entered. Below is the code for my product store class, and my product.cs Any help will be great, thank you. class ProductStore // Attributes { private List _products; // Constructor public ProductStore() { _products = new List(); // Create list of products } // Methods public void AddProduct(Product product) { _products.Add(product); // Add product to list } public void Show() { } } class Program { static void Main(string[] args) { Book genericBook; DVD genericDVD; CD genericCD; ProductStore productStore; productStore = new ProductStore(); genericBook = new Book("", "", "", "", 0); genericDVD = new DVD("", "", "", "", 0.00, ""); genericCD = new CD("", "", "", "", 0.00, ""); int optionNumber = 0; string loop = "Yes"; while (loop == "Yes") { Console.WriteLine("1. Add Book"); Console.WriteLine("2. Add DVD"); Console.WriteLine("3. Add CD"); Console.WriteLine("4. Show Products"); Console.WriteLine("5. Quit"); optionNumber = int.Parse(Console.ReadLine()); switch (optionNumber) { case 1: genericBook.BookTitle(); genericBook.BookAuthor(); genericBook.BookPublisher(); genericBook.BookPrice(); genericBook.BookPackaging(); productStore.AddProduct(genericBook); break; case 2: genericDVD.DVDTitle(); genericDVD.DVDDirector(); genericDVD.DVDActors(); genericDVD.DVDFilmCompany(); genericDVD.DVDPackaging(); genericDVD.DVDPrice(); productStore.AddProduct(genericDVD); break; case 3: genericCD.CDTitle(); genericCD.CDArtist(); genericCD.CDMusicCompany(); genericCD.CDPrice(); genericCD.CDTracks(); genericCD.CDPackaging(); productStore.AddProduct(genericCD); break; case 4: productStore.Show(); break; case 5: Console.WriteLine("Goodbye"); loop = "No"; break; default: Console.WriteLine("Invalid Number - Please choose option 1-5"); break; } } Console.ReadLine(); } }
Joining values of two columns from DataTable   (158 Views)
I am reading a CSV file using a StreamReader and storing the contents in a DataTable. Below is the DataTable format For example imported DataTable (Column 0) (Column 1) etc etc TagNumber, LogNumber etc etc 124 1 125 1 126 2 etc etc etc etc I want to process each row and combine the values of the first two columns of each row so that there will be a combined value e.g "124/1" and modify the datatable so it will have a new column called "Combined" and each row will have its own combined value(see below). For example: (Column 0) (Column 1) TagNumber, LogNumber Combined 124 1 124/1 125 1 125/1 126 2 126/2 etc etc etc etc Here is the code I have written so far but I am difficulty regarding making the changes to the existing DataTable. If you could advise me and provide feedback on the below it would be much appreciated: List myList = new List(); DataTable myDataTable = new DataTable(); StreamReader reader = new StreamReader(filePath); //CSVUtility is my own class which deals with the parsing. myDataTable = CSVUtility.Parse(reader.ReadToEnd(), true); reader.Close(); if(myDataTable.rows.count > 1) { foreach(DataRow dr in myDataTable.rows) { //look at column one(index 0) string valueOne = dr[0].ToString(); //look at column two (index 1) string valueTwo = dr[1].ToString(); string result = valueOne + '/' + valueTwo; //add it to the list myList.add(result); //modify the dataTable //return the modified DatTable for further processing } }