|
Sentenryu wrote: the only thing i don't understand is why i can't call the Select method directly
on the return of Enum.GetValues() , maybe because Array
implements the non-generic IEnumerable interface?
LINQ works on the IQueryable interface, which array's don't support.
Arrays support the following interfaces:
ICloneable, IList, ICollection, IEnumerable, IStructuralComparable and IStructuralEquatable
The .Select extension works on any IEnumerable, including arrays, so I think your .Select example is a bit flawed. I don't know what you're doing, but...
|
|
|
|
|
First of all, i forgot to say thanks for your answer, so Thanks!
In the case i'm just getting a IEnumerable<SelectListItem> with the values of a enum to display as radiobuttons, the actual code (with the excuse of having names in portuguese) is this:
ViewBag.ApetiteOptions = ((IEnumerable<int>)Enum.GetValues(typeof(Apetite))).Select(x => new SelectListItem() {
Text = ((Apetite)x).ToString(),
Value = x.ToString()
});
Visual Studio (2012) gives me an error when I try to use the select method directly on the return type of the
Enum.GetValues() , I guess it's because this method returns a instace of Array (the base class), and not a instance of int[] .
int[] implements IEnumerable<int> , while Array implements IEnumerable , the Select method Expects IEnumerable<TSource> ...
while writting this post, i updated this bit of code to this:
ViewBag.ApetiteOptions = Enum.GetValues(typeof(Apetite)).OfType<int>().Select(x => new SelectListItem() {
Text = ((Apetite)x).ToString(),
Value = x.ToString()
});
I'm a little bit more happy now
I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)
|
|
|
|
|
|
See my answer below, all your LINQ example is missing is a call to
OfType<States>()
|
|
|
|
|
Dave Kreskowiak wrote: LINQ works on the IQueryable interface, which array's don't support.
No, LINQ to SQL / EF works on IQueryable, most of Linq2Objects works on IEnumerable<t>
|
|
|
|
|
Crap. That's what I get with 4 hours of sleep...
|
|
|
|
|
GetValues() does return an enumerable list of the actual enums, so your original code works with VERY few changes:
foreach(var value in Enum.GetValues(typeof(States))){
list.Add(new SelectListItem(){
Text = value.ToString(),
Value = ((int)value).ToString()
});
}
Live example: http://rextester.com/PWOX45762[^]
You can also use LINQ if you want, but that call to Enum.GetValues() returns an Array, so you neeed to call OfType<states>() to coerce it to a generic IEnumerable<states>
var list = Enum.GetValues(typeof(States))
.OfType<States>()
.Select(i => .... );
Live example: http://rextester.com/TRHMMB31708[^]
|
|
|
|
|
Wow, I always thought it returned a Array containing int's, this will really simplify the things! thanks a lot!
I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)
|
|
|
|
|
Hi i'm working out my registration using a three tiered architecture and i'm trying to send the random userid which i got from registering in the aspx page to my custom table which i created. Here is the error i get:
Error 1 'DataClass.ConnectionClass' does not contain a definition for 'ProviderUserKey' and no extension method 'ProviderUserKey' accepting a first argument of type 'DataClass.ConnectionClass' could be found (are you missing a using directive or an assembly reference? Does anyone know how to correct it
here is my presentation layer or the UI layer
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.ApplicationServices;
using System.Data;
using System.Data.SqlClient;
using DataClass;
public partial class Account_Register : System.Web.UI.Page
{
ConnectionClass newobj = new ConnectionClass();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void CreateUserButton_Click(object sender, EventArgs e)
{
string F_Name = txtFirstName.Text;
string L_Name = txtLastName.Text;
string Address = txtAddress.Text;
string City = txtCity.Text;
string State = txtState.Text;
string Zip = txtZipCode.Text;
string DOB = txtDOB.Text;
string Phone = txtPhone.Text;
string email = txtEmail.Text;
string User_Name = txtUserName.Text;
string Password = txtPassword.Text;
string PasswordQuestion = txtPasswordQuestion.Text;
string PasswordAnswer = txtPasswordAnswer.Text;
MembershipCreateStatus createStatus;
MembershipUser newUser = Membership.CreateUser(txtUserName.Text, txtPassword.Text, txtEmail.Text, txtPasswordQuestion.Text, txtPasswordAnswer.Text, true, out createStatus);
switch (createStatus)
{
case MembershipCreateStatus.Success:
string UserId = newUser.ProviderUserKey.ToString();
lblCreateAccount.Text = "The user account was successfully created!";
break;
case MembershipCreateStatus.DuplicateUserName:
lblCreateAccount.Text = "There already exists a user with this username.";
break;
case MembershipCreateStatus.DuplicateEmail:
lblCreateAccount.Text = "There already exists a user with this email address.";
break;
case MembershipCreateStatus.InvalidEmail:
lblCreateAccount.Text = "There email address you provided in invalid.";
break;
case MembershipCreateStatus.InvalidAnswer:
lblCreateAccount.Text = "There security answer was invalid.";
break;
case MembershipCreateStatus.InvalidPassword:
lblCreateAccount.Text = "The password you provided is invalid. It must be seven characters long and have at least one non-alphanumeric character.";
break;
default:
lblCreateAccount.Text = "There was an unknown error; the user account was NOT created.";
break;
}
string userid;
if (newUser != null)
{
userid = newobj.ProviderUserKey.ToString();
newobj.Insert(userid, F_Name, L_Name, Address, City, State, Zip, DOB, Phone,
email, User_Name, Password, PasswordQuestion, PasswordAnswer);
}
}
}
Here is my Data Layer
using System;
using System.Data;
using System.Configuration;
using System.Collections.Specialized;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace DataClass
{
public class ConnectionClass
{
string connStr = ConfigurationManager.ConnectionStrings["aspnetdbConnectionString"].ToString();
public ConnectionClass()
{
}
public int Insert (string U_ID, string F_Name, string L_Name, string Address, string City, string State, string Zip, string DOB, string Phone,
string email, string User_Name, string Password, string PasswordQuestion, string PasswordAnswer)
{
SqlConnection con = new SqlConnection(connStr);
con.Open();
SqlCommand cmd = new SqlCommand("user_membership", con);
cmd.CommandType = CommandType.StoredProcedure;
try {
cmd.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier).Value = new Guid(U_ID);
cmd.Parameters.AddWithValue("@F_Name", F_Name);
cmd.Parameters.AddWithValue("@L_Name", L_Name);
cmd.Parameters.AddWithValue("@Address", Address);
cmd.Parameters.AddWithValue("@City", City);
cmd.Parameters.AddWithValue("@State", State);
cmd.Parameters.AddWithValue("@Zip", Zip);
cmd.Parameters.AddWithValue("@DOB", DOB);
cmd.Parameters.AddWithValue("@Phone", Phone);
cmd.Parameters.AddWithValue("@email", email);
cmd.Parameters.AddWithValue("@User_Name", User_Name);
cmd.Parameters.AddWithValue("@Password", Password);
cmd.Parameters.AddWithValue("@PasswordQuestion", PasswordQuestion);
cmd.Parameters.AddWithValue("@PasswordAnswer", PasswordAnswer);
return cmd.ExecuteNonQuery();
}
catch { throw; }
finally
{
con.Dispose();
con.Close();
cmd.Dispose();
}
}
public DataTable Load(string F_Name, string L_Name, string Address, string City, string State, string Zip, string DOB, string Phone,
string email, string User_Name, string Password, string PasswordQuestion, string PasswordAnswer)
{
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("user_membership", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
try
{
cmd.Parameters.AddWithValue("@F_Name", F_Name);
cmd.Parameters.AddWithValue("@L_Name", L_Name);
cmd.Parameters.AddWithValue("@Address", Address);
cmd.Parameters.AddWithValue("@City", City);
cmd.Parameters.AddWithValue("@State", State);
cmd.Parameters.AddWithValue("@Zip", Zip);
cmd.Parameters.AddWithValue("@DOB", DOB);
cmd.Parameters.AddWithValue("@Phone", Phone);
cmd.Parameters.AddWithValue("@email", email);
cmd.Parameters.AddWithValue("@User_Name", User_Name);
cmd.Parameters.AddWithValue("@Password", Password);
cmd.Parameters.AddWithValue("@PasswordQuestion", PasswordQuestion);
cmd.Parameters.AddWithValue("@PasswordAnswer", PasswordAnswer);
da.Fill(ds);
return ds.Tables[0];
}
catch
{
throw;
}
finally
{
ds.Dispose();
da.Dispose();
conn.Close();
conn.Dispose();
}
}
}
}
|
|
|
|
|
Ahem:
ConnectionClass newobj = new ConnectionClass();
And
userid = newobj.ProviderUserKey.ToString();
Did you mean:
userid = newUser.ProviderUserKey.ToString();
Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water
|
|
|
|
|
Thanks for the response. I can compile it now.
|
|
|
|
|
Hi,
I had a database in access I want to connect through connection string where shall I write the connection string so that it is written once & can be use at different places through out the project.
Second I want to get data in a combobox using that same connection & using a select query at the time of form load in C#
Please suggest .
THanks
|
|
|
|
|
Jaleel Ahmed wrote: where shall I write the connection string so that it is written once & can be use at different places through out the project
Generally it should be in your app.config file.
"Any sort of work in VB6 is bound to provide several WTF moments." - Christian Graus
|
|
|
|
|
Jaleel Ahmed wrote: Second I want to get data in a combobox using that same connection & using a select query at the time of form load in C#
Fire the query in the Form_Load event.
|
|
|
|
|
Hello,
You can use below code to fill Combobox on your form load even.
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = FillDT();
this.cmbTempControl.DataSource = dt;
this.cmbTempControl.ValueMember = "ID";
this.cmbTempControl.DisplayMember = "Name";
}
protected DataTable FillDataTable()
{
DataTable dtTemp = new DataTable();
return dtTemp;
}
Thanks
KiranKumar Roy
|
|
|
|
|
Hi guys, there is a project im working on for a client and im stuck on how to calculate progressive tax based on the income of a particular employee's salary, im not sure about my approach, i wrote a class library in c-sharp for easy portability. Here is the sample code or the library.
namespace TaxCalculator
{
public class ProgressiveTax
{
readonly double limit1 = 0,
limit2 = 10164, limit3 = 10165,
limit4 = 19740, limit5 = 19741,
limit6 = 29316, limit7 = 29317,
limit8 = 38892;
private double taxedAmount = 0;
private double ComputeTax(double grossPay)
{
if ((grossPay >= limit1) && (grossPay <= limit2))
{
taxedAmount = grossPay * 0.1;
return taxedAmount;
}
else if ((grossPay >= limit3) && (grossPay <= limit4))
{
taxedAmount = ComputeTax(limit2) + ((grossPay - limit2) * 0.15);
return taxedAmount;
}
else if ((grossPay >= limit5) && (grossPay <= limit6))
{
taxedAmount = ComputeTax(limit4) + ((grossPay - limit4) * 0.2);
return taxedAmount;
}
else if ((grossPay >= limit7) && (grossPay <= limit8))
{
taxedAmount = ComputeTax(limit6) + ((grossPay - limit6) * 0.25);
return taxedAmount;
}
else if ((grossPay > limit8))
{
taxedAmount = ComputeTax(limit8) + ((grossPay - limit8) * 0.3);
return taxedAmount;
}
return 0;
}
public double ComputeNet(double netSalary = 0)
{
netSalary = netSalary - ComputeTax(netSalary);
return netSalary;
}
public double GetTax(double salaryAmount)
{
salaryAmount = ComputeTax(salaryAmount);
return salaryAmount;
}
}
}
|
|
|
|
|
What happens if the tax rates or limits change? The data should be stored in a table somewhere, and read in at run time - you would then store it in a class or structure like this:
public class TaxRates
{
public double UpperLimit;
public double LowerLimit;
public double Deductible;
public double CalcRate;
} Populate a list of these from your table and then all you need do is iterate looking for the value where the value is between lower and upper and then use this to form the basis of your calculation. Also, you should note that your sample code has holes in it. What happens if someone earns 10164.01?
|
|
|
|
|
Pete O'Hanlon wrote: What happens if the tax rates or limits change? The data should be stored in a table somewhere, and read in at run time
I agree. Hard coded values in programs should always be kept to a minimum.
"Any sort of work in VB6 is bound to provide several WTF moments." - Christian Graus
|
|
|
|
|
Question: best place to obtain return code from a proxy
I am enhancing on a C# 2008 application that calls a web service. This application was written by the contract shop that has the web service. I am just adding what I need to this application for my company's needs.
One change I am making is for my company to have a tracking table. This table is used to keep track of the types of calls that have been made to the web service for each of our customers.
"My question is the best place to obtain the return code from the web service".
Right now there is a proxy that is used in this application to call the web service. The proxy contains the return code from the web service.
Thus I am looking for best place to obtain the return code from the proxy and how would you make the coding change from the list below and/or other options you can think of:
1. Can I put my code in the proxy? I would not touch the exact location where the web service is called. Is this a good idea or not?
2. When I use the proxy I would change it to a function. The value returned from the function call would be the value I am looking for.
3. I would pass an extra parameter to the proxy call to it would give me the return code. if I chose this option, how would I obtain the value that is optional a return value from the proxy call?
|
|
|
|
|
It depends. It *always* depends.
I would try to look for a solution that could keep the tracking stuff separate from the proxy. Proxies usually aren't hand-coded and it's quite convenient to just "update" a "service reference" in order to generate new proxy code should the service interface change.
Assuming you only use a few operations on the service, the easiest seems to me to be adding a thin abstraction layer on top of the proxy and put the tracking logic there.
A few tips for how to do such refactoring speedily:
- Rename the proxy class to whatever you want your new class (implementing the abstraction layer) to have, using Refactor => Rename. This will update all the call sites.
- Rename the class back to what it was originally called, WITHOUT using Refactor => Rename.
Every place in the code where you had new Proxy() you now have new AbstractionLayer(). (Please don't use that name. Name it according to what function it has.)
Introduce the new class and put your tracking logic there. In short, you've built a proxy for the proxy.
|
|
|
|
|
Thank you, this saves me having to answer the question. Of course, I would use the term Facade rather than AbstractionLayer. My 5 anyway.
|
|
|
|
|
Well that's what we get with metaphores. If you're speaking pattern what you're saying may be well-defined, but as long as we just use metaphores things are always kinda vague.
A proxy is a kind of facade and also a kind of abstraction layer, wouldn't you say?
But to my mind, the facade metaphor is a little inappropriate here because the thing about a facade is that it looks completely different from what it's hiding. That's usually the point of having a facade, to cover the ugly stuff. A proxy on the other hand looks just like the thing it is a proxy for. So here I think we're making a proxy for the proxy. But rather than start explaining all this and use "metaproxy" I resorted to the more general conception of an abstraction layer.
Of course, in practice one would only expose those bits of the interface that one actually uses. So then I suppose it kinda acts as a facade too...
Gee it's hard to say anything sensible about this stuff. As a programmer one ventures to the borders of philosophy all the time. But then that's one of the things I find appealing!
|
|
|
|
|
So you think that the proxy should expose a few values like the return code so that I can use it correct?
|
|
|
|
|
I'm not sure what you mean by that. It should "expose" the return value *as* a return value. Externally, it's useage should be identical to your original proxy, but internally it should call the proxy, update tracking information, and return whatever the proxy returned.
Perhaps we are talking past one another. What I mean is you have some generated proxy like this:
class Proxy
{
public int Foo()
{
}
}
and some code that uses it,
class UserCode
{
void Bar()
{
var x = new Proxy().Foo();
}
}
You can now introduce a "metaproxy",
class MetaProxy
{
int clientID;
Proxy proxy = new Proxy();
public MetaProxy(int clientID)
{
this.clientID = clientID;
}
public int Foo()
{
var x = proxy.Foo();
Tracking.Register("Foo", clientID, x);
return x;
}
}
Lastly of course the user code must be modified to use MetaProxy instead of Proxy.
I don't know the details of what sort of tracking you really need to do. Nor do I know, or want to know , everything needed to say if this is how you should obtain the information you need (examplified by "clientID"). If you have this information everywhere you are making such calls, perhaps this is a good way of doing it. If you don't, and this is in an application processing requests (so that everything that happens in a thread happens on behalf of a particular client) perhaps it'd be nice to put the clientID in a ThreadStatic instead, and then your MetaProxy could just have a default constructor and sniff out the clientID from there.
So you still have to do your own thinking. But hopefully this will make it clear how I propose you can establish tracking. Of course just keeping track of things is not going to do anything more than that.
|
|
|
|
|
Hi,
I have a requirement to render the contents from excel to word. With a condition that the content after rendering to word should look like they way it is displayed in print preview mode of excel. Can anybody help me on this?
To give additional information, I need the properites set in excel also to be rentered while rendering to word.
For example: If the mode is set to landscape in excel I want the same mode to be set in word after rendering. Similar with boarders, margins, print area and scalings.
Thanks
Ullas Joseph
|
|
|
|
|