|
The problem is that the third party dll uses float value in its class.
So I really cant get rid of the float and I still need to use this dll.
As a work around I am using Math.Abs() method to find out tolerable difference between the two float values instead of checking exact difference using "==" with floats.
|
|
|
|
|
|
Thanks you Led.
The link is quite useful.
|
|
|
|
|
hello, math.round donot support float, its argument must be Double.
for example :
Double dblValue = 123.126789;
dblValue = Math.Round(dblValue, 2);
MessageBox.Show(dblValue.ToString());// Displays 123.13
I think u can continue your work.
Best of Luck.
Dipak
|
|
|
|
|
Sorry, you're mistaken. Your example happens to produce the result you want, but it is
not correct. Here is the background:
The way floats/doubles are stored in binary makes it impossible to exactly represent
most values, especially the ones that seem like round numbers to humans thinking
using base ten.
So 4, 2, 1, 0.5, 3.5, 3.75 and many others are representable exactly (basically since
they all equal an integer divided by some power of 2); but 3.6 and 3.8 and an infinite
number of other values are not.
Now whatever float/double function you call, if it returns a float/double will suffer
from the same phenomenon. So the only way to really get "3.6" or "3.8" is by using a
function that not only rounds but returns a string. I trust there are some formatting
methods that do just that in every programming language; In .NET languages
ToString() should be one of them, given an appropriate format specifier.
If you want to know much more about this topic, here it is:
http://docs.sun.com/source/806-3568/ncg_goldberg.html
BTW: to circumvent the floating-point rounding problem, especially for monetary
numbers, they introduced the "decimal" data type (which basically stores decimal
digits).
|
|
|
|
|
hi
I started to work with the VS2008 & FrameWork 3.5
if i want that my programs will run on any computer i need the FrameWork 3.5
is it weight so match? 200MB ???
there is version that weight 2.5MB but the installation is from the WEB
is there any version of FrameWork 3.5 that weight less then 200MB ? and don't need installation
from the WEB ?
thank's
|
|
|
|
|
E_Gold wrote: is it weight so match? 200MB ???
It doesn't "weigh" that much. Remember that it only has to be installed once regardless of how many .NET 3.5 applicaitons get installed on the PC.
E_Gold wrote: there is version that weight 2.5MB but the installation is from the WEB
No. That is a bootstrapper. The bootstrapper is 2.7Mb. The actual .NET Framework is still the same size. You just have an easier download.
E_Gold wrote: is there any version of FrameWork 3.5 that weight less then 200MB ?
Yes, the version you quote, pedantically speaking, "weighs" less than 200Mb. It is only 197Mb
|
|
|
|
|
E_Gold wrote: there is version that weight 2.5MB but the installation is from the WEB
Like Colin said, that is just for doing web-based install. You still have to install the rest through the setup program.
"Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks" - Pete O'Hanlon
|
|
|
|
|
using System;
using System.Text;
using System.IO;
using System.Web;
using System.Net;
using System.Collections.Specialized;
using System.Web;
namespace Snowball.Common
{
///
/// Submits post data to a url.
///
public class PostSubmitter
{
public int byteleng;
///
/// determines what type of post to perform.
///
public enum PostTypeEnum
{
///
/// Does a get against the source.
///
Get,
///
/// Does a post against the source.
///
Post
}
private string m_url = string.Empty;
private NameValueCollection m_values = new NameValueCollection();
private PostTypeEnum m_type = PostTypeEnum.Get;
///
/// Default constructor.
///
public PostSubmitter()
{
}
///
/// Constructor that accepts a url as a parameter
///
/// <param name="url" />The url where the post will be submitted to.
public PostSubmitter(string url)
: this()
{
m_url = url;
}
///
/// Constructor allowing the setting of the url and items to post.
///
/// <param name="url" />the url for the post.
/// <param name="values" />The values for the post.
public PostSubmitter(string url, NameValueCollection values)
: this(url)
{
m_values = values;
}
///
/// Gets or sets the url to submit the post to.
///
public string Url
{
get
{
return m_url;
}
set
{
m_url = value;
}
}
///
/// Gets or sets the name value collection of items to post.
///
public NameValueCollection PostItems
{
get
{
return m_values;
}
set
{
m_values = value;
}
}
///
/// Gets or sets the type of action to perform against the url.
///
public PostTypeEnum Type
{
get
{
return m_type;
}
set
{
m_type = value;
}
}
///
/// Posts the supplied data to specified url.
///
/// <returns>a string containing the result of the post.
public string Post()
{
StringBuilder parameters = new StringBuilder();
for (int i = 0; i < m_values.Count; i++)
{
EncodeAndAddItem(ref parameters, m_values.GetKey(i), m_values[i]);
}
string result = PostData(m_url, parameters.ToString());
return result;
}
///
/// Posts the supplied data to specified url.
///
/// <param name="url" />The url to post to.
/// <returns>a string containing the result of the post.
public string Post(string url)
{
m_url = url;
return this.Post();
}
///
/// Posts the supplied data to specified url.
///
/// <param name="url" />The url to post to.
/// <param name="values" />The values to post.
/// <returns>a string containing the result of the post.
public string Post(string url, NameValueCollection values)
{
m_values = values;
return this.Post(url);
}
///
/// Posts data to a specified url. Note that this assumes that you have already url encoded the post data.
///
/// <param name="postData" />The data to post.
/// <param name="url" />the url to post to.multipart/form-data; boundary=
/// <returns>Returns the result of the post.
private string PostData(string url, string postData)
{
// string sa="";
HttpWebRequest request = null;
if (m_type == PostTypeEnum.Post)
{
Uri uri = new Uri(url);
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytess = encoding.GetBytes(postData);
request.ContentType = "multipart/form-data; boundary=" + "---------------------" + DateTime.Now.Ticks.ToString("x"); //;//application/x-www-form-urlencoded
request.ContentLength = bytess.Length;// postData.Length;
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding1 = new UTF8Encoding();
byte[] bytes = encoding1.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
}
}
else
{
Uri uri = new Uri(url + "?" + postData);
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
}
string result = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
return result;
}
///
/// Encodes an item and ads it to the string.
///
/// <param name="baseRequest" />The previously encoded data.
/// <param name="dataItem" />The data to encode.
/// <returns>A string containing the old data and the previously encoded data.
private void EncodeAndAddItem(ref StringBuilder baseRequest, string key, string dataItem)
{
if (baseRequest == null)
{
baseRequest = new StringBuilder();
}
if (baseRequest.Length != 0)
{
baseRequest.Append("&");
}
baseRequest.Append(key);
baseRequest.Append("=");
baseRequest.Append(System.Web.HttpUtility.UrlEncode(dataItem));
}
}
}
--------------
byte[] Image = (byte[])ImagePicture;
string picture1 = Convert.ToBase64String(Image);
PostSubmitter post = new PostSubmitter();
post.Url = "http://.....";
post.PostItems.Add("Body/ad/category_id", "2");
post.PostItems.Add("Body/ad/language_code", "1");
post.PostItems.Add("Body/ad/format", "1");
post.PostItems.Add("Body/ad/price_type", "1");
post.PostItems.Add("Body/ad/ask_price", "112345.67");
post.PostItems.Add("Body/ad/title", "TEST IT-Pictures");
post.PostItems.Add("Body/ad/description", "TEST IT-Pictures");
post.PostItems.Add("Body/image1", picture1);
post.Type = PostSubmitter.PostTypeEnum.Post;
string result = post.Post();
It outputs an error! Help, what's wrong, I think that erroc in
private string PostData(string url, string postData)
and exactly in this string:
request.ContentType = "multipart/form-data; boundary=" + "---------------------" + DateTime.Now.Ticks.ToString("x");
|
|
|
|
|
cd_dvd wrote: It outputs an error!
What error?
Vasudevan Deepak Kumar
Personal Homepage Tech Gossips
A pessimist sees only the dark side of the clouds, and mopes; a philosopher sees both sides, and shrugs; an optimist doesn't see the clouds at all - he's walking on them. --Leonard Louis Levinson
|
|
|
|
|
There is no error in the code(the compilation results in 0 errors), but the result is not the one I want.
It should send information with a picture, but the server don't received anything. When I send data with method
application/x-www-form-urlencoded this code sended all information without a picture. The picture should be send as multipart/form-data. When using "application/x-www-form-urlencoded" the response from server contained the ID of the record added, but the picture wasn't.
|
|
|
|
|
I would like to have a method that does something like the following,
public static object foo(object A, Type T) {
return (T)A;
} I don't explicitly know the type T anywhere in my code... it is found at runtime, so I CAN'T do the following (unless there is some way to send TObject.GetType() as T):
public static T foo<T>(object A) {
return (T)A;
} Oh, and object A cannot implement the IConvertable Interface (or any interface, for that matter, since I have NO control over the class), so I am unable to use the System.Convert.ChangeType method as well. I DO however know that either
1: type T defines an explicit cast operator from AType->T, OR
2: type AType defines an explicit cast operator from AType->T
but I can't figure out how to call that cast with the information I have. Does anyone know a way that I can accomplish this? Thanks,
Sounds like somebody's got a case of the Mondays
-Jeff
|
|
|
|
|
Have you tried the "ChangeType" method of the "Convert" class?
It seems to be exactly your foo
|
|
|
|
|
"Convert.ChangeType" seems to be exactly your foo
|
|
|
|
|
Yes, but to call that method the object must implement IConvertible (or at least, that's the exception I got at runtime when I tried it). The answer I used was given in the next post, but thanks for taking the time to help!
Sounds like somebody's got a case of the Mondays
-Jeff
|
|
|
|
|
Hi
Basically an Operator is a static method, that you can call via reflection if you know the name of it.
let's say you have a class A and a class B
they look like this:
public class A
{
public static implicit operator B(A SourceObject)
{
return new B();
}
}
public class B
{
}
then the compiler compiles the operator as
public static B op_implicit(A SourceObject);
so, all you have to do, is to use reflection to find the static method that's called
op_implicit , takes an object of A as parameter and returns an object of B
hope this helps
greets
m@u
|
|
|
|
|
Thanks! My final code for the method in question is copied below:
private static readonly string[] s_CastOps = new string[] { "op_Explicit", "op_Implicit" };
public static T Convert<T, U>(U other) where T : new() {
T rval = new T();
foreach (PropertyInfo tPropInfo in typeof(T).GetProperties()) {
if (tPropInfo.GetCustomAttributes(typeof(System.Xml.Serialization.XmlIgnoreAttribute), true).Length > 0)
continue;
PropertyInfo uPropInfo = typeof(U).GetProperty(tPropInfo.Name);
if (uPropInfo != null && tPropInfo.CanWrite && uPropInfo.CanRead
&& uPropInfo.GetIndexParameters().Length == 0
&& tPropInfo.GetIndexParameters().Length == 0) {
Type tPropType = tPropInfo.PropertyType;
Type uPropType = uPropInfo.PropertyType;
if (tPropType.Equals(uPropType)) {
tPropInfo.SetValue(rval, uPropInfo.GetValue(other, null), null);
continue;
}
Type[] uPropTypeArray = new Type[] { uPropType };
object[] uValue = new object[] { uPropInfo.GetValue(other, null) };
ConstructorInfo tConstruct = tPropType.GetConstructor(uPropTypeArray);
if (tConstruct != null) {
tPropInfo.SetValue(rval, tConstruct.Invoke(uValue), null);
continue;
}
foreach (Type propType in new Type[] { tPropType, uPropType }) {
foreach (string castOp in s_CastOps) {
MethodInfo ConvertUtoT = propType.GetMethod(castOp, uPropTypeArray);
if (ConvertUtoT != null && tPropType.Equals(ConvertUtoT.ReturnType)) {
tPropInfo.SetValue(rval, ConvertUtoT.Invoke(null, uValue), null);
goto _endConvert;
}
}
}
_endConvert:
continue;
}
}
return rval;
} Basically, I go through the list of properties on both types. If both have a property with the same name, I try to copy the value from one to the other. If they are the same type, I simply set one to the other. Otherwise, I check if the result type has a constructor that takes the source type as a parameter. If so, I call the constructor. If not, then I look for a typecast definition between the two types (either explicit or implicit). If found, I cast the value of the source property to the type of the target property. This works great to copy objects with the same (or similar) properties into different types. Thanks for the help!
Sounds like somebody's got a case of the Mondays
-Jeff
|
|
|
|
|
Hi,
I need to determine user role, especially if user is administrator. I know one way, but that way doesn't provide the information I need:
WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
principal.IsInRole(WindowsBuiltInRole.Administrator);
the problem is that even if user is an administrator (on Vista) and the UAC is on , user still behaves like non-administrator user. Difference is when a UAC form is displayed. When an administrator is required to elevale a process to admin rights, he doesn't need to type in his (administrator) credentials. However a regular user does have to type in these credentianls (of course). So if an application is run under administrator but not elevated to administrator rights, the principal says that the Current User is not an administrator. I need to know if that user is an administrator not depending on current Thread/Appication granted rights.
thanx in advance...
zilo
|
|
|
|
|
I managed to do this by adding this class to my application:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Principal;
namespace Gauge
{
public static class mySecurity
{
#region Constants
const UInt32 TOKEN_QUERY = 8;
const int INT_SIZE = 4;
#endregion
#region Enumerations
private enum TOKEN_ELEVATION_TYPE
{
TokenElevationTypeDefault = 1,
TokenElevationTypeFull,
TokenElevationTypeLimited
}
public enum TOKEN_INFO_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
TokenElevationType,
TokenLinkedToken,
TokenElevation,
TokenHasRestrictions,
TokenAccessInformation,
TokenVirtualizationAllowed,
TokenVirtualizationEnabled,
TokenIntegrityLevel,
TokenUIAccess,
TokenMandatoryPolicy,
TokenLogonSid,
MaxTokenInfoClass
// MaxTokenInfoClass should always be the last enum
}
#endregion
#region WIN API FUNCTIONS
[DllImport("kernel32.dll")]
public static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", SetLastError=true)]
public static extern Boolean OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);
[DllImport("advapi32.dll", SetLastError=true)]
public static extern Boolean GetTokenInformation(IntPtr TokenHandle, TOKEN_INFO_CLASS TokenInformationClass,
IntPtr TokenInformation, int TokenInformationLength, out uint ReturnLength);
#endregion
#region Public Methods
///
/// Returns True when the current user is a member of the
/// Administrators group and is also running the process
/// elevated as an Administrator, otherwise returns false.
///
/// <returns>
/// <c>true if user is running the process elevated as an Administrator; otherwise, <c>false.
///
public static Boolean IsRunningAsAdmin(WindowsPrincipal pWindowsPrincipal)
{
return pWindowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
}
///
/// Checks whether the user can elevate to Administrator rights.
///
/// <returns><c>true if user can elevate to Administrator rights; <c>false otherwise.
public static Boolean CanElevateToAdmin(WindowsPrincipal pWindowsPrincipal)
{
Boolean returnVal = false;
// Determine if the current user is already running with Administrator rights.
Boolean isAdmin = IsRunningAsAdmin(pWindowsPrincipal);
// Return True if the user is an Administrator (user must have Administration rights).
if (isAdmin)
return true;
OperatingSystem os = Environment.OSVersion;
Version vs = os.Version;
// If Vista or Higher, check for split token.
if (vs.Major > 5)
{
try
{
IntPtr myToken;
TOKEN_ELEVATION_TYPE elevationType;
uint dwSize;
IntPtr pElevationType = Marshal.AllocHGlobal(INT_SIZE);
// Get a token reference for the user running this process.
OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, out myToken);
// Get the elevation information for this token.
GetTokenInformation(myToken, TOKEN_INFO_CLASS.TokenElevationType, pElevationType,
INT_SIZE, out dwSize);
// Cast the result to ENUM_TYPE.
elevationType = (TOKEN_ELEVATION_TYPE)(Marshal.ReadInt32(pElevationType));
// Free allocated unmanaged memory.
Marshal.FreeHGlobal(pElevationType);
// Determine result of the elevation check.
// ==============================================
// TokenElevationTypeFull - User has a split token,
// and the process is running elevated
// TokenElevationTypeDefault - User is not using a split token
// ==============================================
returnVal = (elevationType == TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited);
returnVal = returnVal || (elevationType == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull);
}
catch
{
returnVal = false;
}
}
else
{
// Prior to Vista, only check needed is if user is in Administrators group.
returnVal = isAdmin;
}
return returnVal;
}
///
/// Checks if user is running as a standared user, but can elevate to Administrator rights.
///
/// <returns><c>true if user can elevate with their own credentials; <c>false otherwise.
|
|
|
|
|
Hi everybody,
how can i use TAPI 2 into C#?
I made my project with TAPI 3, but the 3rd Version is buggy, the DISCONNECTED Event doesn't fire
each time if the call is over.
So i like to step to Version 2 of TAPI
Big thanks for help
|
|
|
|
|
Hi
i have the following code which insetrs a value into the database, however it says the value is not in the correct format.
any help?
thanks
Session["Qty_New"] = tb_Qty_New.Text.;
cmd.Parameters.Add(new SqlParameter("@qty_new", SqlDbType.Int));
cmd.Parameters["@qty_new"].Value = Convert.ToInt32(Session["Qty_New"]);
|
|
|
|
|
Jamie1985 wrote: wever it says the value is not in the correct format.
any help?
Yes, obviously ensure Session["Qty_New"] has data, and that that data can be converted to an int before converting it.
Check out int.TryParse rather than Convert.ToInt32
|
|
|
|
|
Two things - you don't actually need to convert the session to an int to assign it to the parameter. Also, you should check to see if Session["Qty_New"] is null or an empty string before using it.
|
|
|
|
|
Hi
are you sure i dont need to convert to int, i took it out and left it like this
string Qty_New
Qty_New = tb_Qty_New.Text;
cmd.Parameters.Add(new SqlParameter("@qty_new", SqlDbType.Int));
cmd.Parameters["@qty_new"].Value = Qty_New;
however this doesnt work
there is a value in Qty_New
cheers
|
|
|
|
|
Any leading/trailing space character in that?
Vasudevan Deepak Kumar
Personal Homepage Tech Gossips
A pessimist sees only the dark side of the clouds, and mopes; a philosopher sees both sides, and shrugs; an optimist doesn't see the clouds at all - he's walking on them. --Leonard Louis Levinson
|
|
|
|
|