Search Results

Search found 1193 results on 48 pages for 'decimal'.

Page 12/48 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Fluent nHibernate and mapping IDictionary<DaysOfWeek,IDictionay<int, decimal>> how to?

    - by JS Future Software
    Hello, I have problem with making mapping of classes with propert of type Dictionary and value in it of type Dictionary too, like this: public class Class1 { public virtual int Id { get; set; } public virtual IDictionary<DayOfWeek, IDictionary<int, decimal>> Class1Dictionary { get; set; } } My mapping looks like this: Id(i => i.Id); HasMany(m => m.Class1Dictionary); This doesn't work. The important thing I want have everything in one table not in two. WHet I had maked class from this second IDictionary I heve bigger problem. But first I can try like it is now.

    Read the article

  • Sorting a list of variable length integers delimited by decimal points...

    - by brewerdc
    Hey guys, I'm in need of some help. I have a list of delimited integer values that I need to sort. An example: Typical (alpha?) sort: 1.1.32.22 11.2.4 2.1.3.4 2.11.23.1.2 2.3.7 3.12.3.5 Correct (numerical) sort: 1.1.32.22 2.1.3.4 2.3.7 2.11.23.1.2 3.12.3.5 11.2.4 I'm having trouble figuring out how to setup the algorithm to do such a sort with n number of decimal delimiters and m number of integer fields. Any ideas? This has to have been done before. Let me know if you need more information. Thanks a bunch! -Daniel

    Read the article

  • Doing arithmetic with up to two decimal places in Python?

    - by user248237
    I have two floats in Python that I'd like to subtract, i.e. v1 = float(value1) v2 = float(value2) diff = v1 - v2 I want "diff" to be computed up to two decimal places, that is compute it using %.2f of v1 and %.2f of v2. How can I do this? I know how to print v1 and v2 up to two decimals, but not how to do arithmetic like that. The particular issue I am trying to avoid is this. Suppose that: v1 = 0.982769777778 v2 = 0.985980444444 diff = v1 - v2 and then I print to file the following: myfile.write("%.2f\t%.2f\t%.2f\n" %(v1, v2, diff)) then I will get the output: 0.98 0.99 0.00, suggesting that there's no difference between v1 and v2, even though the printed result suggests there's a 0.01 difference. How can I get around this? thanks.

    Read the article

  • Parse both symbols . and , as decimal digits delimiter in ASP.NET

    - by abatishchev
    I'm writing a banking system and my customer wants support both Russian and American numeric standards in decimal digits delimiter. Respectively . and ,. Now only , works properly. Perhaps because of web server's OS format (Russian is set). String like 2000.00 throws a FormatException: Input string was not in a correct format. How to fix that? Are there any other ideas except String.Replace('.', ',') on FormView.ItemInserting event?

    Read the article

  • What is the best way to find the digit at n position in a decimal number?

    - by Elijah
    Background I'm working on a symmetric rounding class and I find that I'm stuck with regards to how to best find the number at position x that I will be rounding. I'm sure there is an efficient mathematical way to find the single digit and return it without having to resort to string parsing. Problem Suppose, I have the following (C#) psuedo-code: var position = 3; var value = 102.43587m; // I want this no ? (that is 5) protected static int FindNDigit(decimal value, int position) { // This snippet is what I am searching for } Also, it is worth noting that if my value is a whole number, I will need to return a zero for the result of FindNDigit. Does anyone have any hints on how I should approach this problem? Is this something that is blaringly obvious that I'm missing?

    Read the article

  • How can I convert a decimal to a fraction ?

    - by CornyD
    How do I convert a indefinite decimal (i.e. .333333333...) to a string fraction representation (i.e. "1/3"). I am using VBA and the following is the code I used (i get an overflow error at the line "b = a Mod b": Function GetFraction(ByVal Num As Double) As String If Num = 0# Then GetFraction = "None" Else Dim WholeNumber As Integer Dim DecimalNumber As Double Dim Numerator As Double Dim Denomenator As Double Dim a, b, t As Double WholeNumber = Fix(Num) DecimalNumber = Num - Fix(Num) Numerator = DecimalNumber * 10 ^ (Len(CStr(DecimalNumber)) - 2) Denomenator = 10 ^ (Len(CStr(DecimalNumber)) - 2) If Numerator = 0 Then GetFraction = WholeNumber Else a = Numerator b = Denomenator t = 0 While b <> 0 t = b b = a Mod b a = t Wend If WholeNumber = 0 Then GetFraction = CStr(Numerator / a) & "/" & CStr(Denomenator / a) Else GetFraction = CStr(WholeNumber) & " " & CStr(Numerator / a) & "/" & CStr(Denomenator / a) End If End If End If End Function

    Read the article

  • How to enter decimal/binary numbers when creating byte objects in python?

    - by Eric
    I'm using python 3.1.1. I know that I can create byte objects using the byte literal in the form of b'...'. In these byte objects, each byte can be represented as a character(in ascii code if I'm not wrong) or as a hexadecimal/octal number. Hexadecimal and octal numbers can be entered using an escape of \x for hexadecimal numbers and just a \ for octal numbers. However, there's no escape sequences for decimal or binary numbers. Is there any way to enter them into byte objects?

    Read the article

  • How to create a generic C# method that can return either double or decimal?

    - by CrimsonX
    I have a method like this: private static double ComputePercentage(ushort level, ushort capacity) { double percentage; if(capacity == 1) percentage = 1; // do calculations... return percentage; } Is it possible to make it of a generic type like "type T" where it can return either decimal or double, depending on the type of method expected (or the type put into the function?) I tried something like this and I couldn't get it to work, because I cannot assign a number like "1" to a generic type. I also tried using the "where T :" after ushort capacity) but I still couldn't figure it out. private static T ComputePercentage<T>(ushort level, ushort capacity) { T percentage; if(capacity == 1) percentage = 1; // error here // do calculations... return percentage; } Is this even possible? I wasn't sure, but I thought this post might suggest that what I'm trying to do is just plain impossible.

    Read the article

  • Bit-Twiddling in SQL

    - by Mike C
    Someone posted a question to the SQL Server forum the other day asking how to count runs of zero bits in an integer using SQL. Basically the poster wanted to know how to efficiently determine the longest contiguous string of zero-bits (known as a run of bits) in any given 32-bit integer. Here are a couple of examples to demonstrate the idea: Decimal = Binary = Zero Run 999,999,999 decimal = 00 111011 1 00 11010 11 00 1 00 1 11111111 binary = 2 contiguous zero bits 666,666,666 decimal = 00100111 10111100...(read more)

    Read the article

  • Green (Screen) Computing

    - by onefloridacoder
    I recently was given an assignment to create a UX where a user could use the up and down arrow keys, as well as the tab and enter keys to move through a Silverlight datagrid that is going be used as part of a high throughput data entry UI. And to be honest, I’ve not trapped key codes since I coded JavaScript a few years ago.  Although the frameworks I’m using made it easy, it wasn’t without some trial and error.    The other thing that bothered me was that the customer tossed this into the use case as they were delivering the use case.  Fine.  I’ll take a whack at anything and beat up myself and beg (I’m not beyond begging for help) the community for help to get something done if I have to. It wasn’t as bad as I thought and I thought I would hopefully save someone a few keystrokes if you wanted to build a green screen for your customer.   Here’s the ValueConverter to handle changing the strings to decimals and then back again.  The value is a nullable valuetype so there are few extra steps to take.  Usually the “ConvertBack()” method doesn’t get addressed but in this case we have two-way binding and the converter needs to ensure that if the user doesn’t enter a value it will remain null when the value is reapplied to the model object’s setter.  1: using System; 2: using System.Windows.Data; 3: using System.Globalization; 4:  5: public class NullableDecimalToStringConverter : IValueConverter 6: { 7: public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 8: { 9: if (!(((decimal?)value).HasValue)) 10: { 11: return (decimal?)null; 12: } 13: if (!(value is decimal)) 14: { 15: throw new ArgumentException("The value must be of type decimal"); 16: } 17:  18: NumberFormatInfo nfi = culture.NumberFormat; 19: nfi.NumberDecimalDigits = 4; 20:  21: return ((decimal)value).ToString("N", nfi); 22: } 23:  24: public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 25: { 26: decimal nullableDecimal; 27: decimal.TryParse(value.ToString(), out nullableDecimal); 28:  29: return nullableDecimal == 0 ? null : nullableDecimal.ToString(); 30: } 31: }            The ConvertBack() method uses TryParse to create a value from the incoming string so if the parse fails, we get a null value back, which is what we would expect.  But while I was testing I realized that if the user types something like “2..4” instead of “2.4”, TryParse will fail and still return a null.  The user is getting “puuu-lenty” of eye-candy to ensure they know how many values are affected in this particular view. Here’s the XAML code.   This is the simple part, we just have a DataGrid with one column here that’s bound to the the appropriate ViewModel property with the Converter referenced as well. 1: <data:DataGridTextColumn 2: Header="On-Hand" 3: Binding="{Binding Quantity, 4: Mode=TwoWay, 5: Converter={StaticResource DecimalToStringConverter}}" 6: IsReadOnly="False" /> Nothing too magical here.  Just some XAML to hook things up.   Here’s the code behind that’s handling the DataGridKeyup event.  These are wired to a local/private method but could be converted to something the ViewModel could use, but I just need to get this working for now. 1: // Wire up happens in the constructor 2: this.PicDataGrid.KeyUp += (s, e) => this.HandleKeyUp(e);   1: // DataGrid.BeginEdit fires when DataGrid.KeyUp fires. 2: private void HandleKeyUp(KeyEventArgs args) 3: { 4: if (args.Key == Key.Down || 5: args.Key == Key.Up || 6: args.Key == Key.Tab || 7: args.Key == Key.Enter ) 8: { 9: this.PicDataGrid.BeginEdit(); 10: } 11: }   And that’s it.  The ValueConverter was the biggest problem starting out because I was using an existing converter that didn’t take nullable value types into account.   Once the converter was passing back the appropriate value (null, “#.####”) the grid cell(s) and the model objects started working as I needed them to. HTH.

    Read the article

  • NHibernate unmapped class exception

    - by John Prideaux
    I am trying to implement a one-to-many relationship using NHibernate 2.1.2 but keep getting "Association references unmapped class" exceptions. I have verified that my hbm.xml files are embedded resource. Here are my classes and mappings. Any ideas? public class OrderStatus { public virtual decimal MainCommit { get; set; } public virtual decimal CommitNumber { get; set; } public virtual string InvoiceNumber { get; set; } public virtual string ShipTo { get; set; } public virtual string CustomerOrderNumber { get; set; } public virtual string Station { get; set; } public virtual DateTime RequestedShipDate { get; set; } public virtual decimal EstimatedValue { get; set; } public virtual decimal EstimatedWeight { get; set; } public virtual string Customer { get; set; } public virtual DateTime InvoiceDate { get; set; } public virtual ICollection<Promise> Promises { get; set; } } <class name="AladdinDb.Models.OrderStatus, AladdinDb" table="vorder_status"> <id name="CommitNumber" type="decimal" column="commit_no"> <generator class="assigned"> <param name="property"> Plan </param> </generator> </id> <property name="MainCommit" column="main_commit" type="decimal" /> <property name="InvoiceNumber" column="invoice_no" type="string" /> <property name="ShipTo" column="ship_to" type ="string"/> <property name="CustomerOrderNumber" column="cust_order_no" type="string" /> <property name="Station" column="station" type="string" /> <property name="RequestedShipDate" column="req_ship_date" type="DateTime" /> <property name="EstimatedValue" column="estimated_value" type="decimal"/> <property name="EstimatedWeight" column="estimated_weight" type="decimal" /> <property name="Customer" column="customer" type="string" /> <property name="InvoiceDate" column="invoice_date" /> <set name="Promises"> <key column="commit_no"></key> <one-to-many class="Promise" /> </set> </class> public class Promise { public virtual decimal CommitNumber { get; set; } public virtual DateTime PromiseDate { get; set; } public virtual string WhoAsked { get; set; } public virtual string WhoGave { get; set; } public virtual string Iffy { get; set; } } <class name="AladdinDb.Models.Promise, AladdinDb" table="promise"> <id name="CommitNumber" type="decimal" column="commit_no"> <generator class="assigned" /> </id> <property name="PromiseDate" column="promise_date" /> <property name="WhoAsked" column="who_asked" /> <property name="WhoGave" column="who_gave" /> <property name="Iffy" column="iffy" /> </class>

    Read the article

  • Jqyery Bugs?? Long decimal number after two numbers multiply...

    - by Jerry
    Hi all I am working on a shopping site and I am trying to calculate the subtotal of products. I got my price from a array and quantity from getJSON response array. Two of them multiply comes to my subtotal. I can change the quantity and it will comes out different subtotal. However,when I change the quantity to certain number, the final subtotal is like 259.99999999994 or some long decimal number. I use console.log to check the $price and $qty. Both of them are in the correct format ex..299.99 and 6 quantity.I have no idea what happen. I would appreciate it if someone can help me about it. Here is my Jquery code. $(".price").each(function(index, price){ $price=$(this); //get the product id and the price shown on the page var id=$price.closest('tr').attr('id'); var indiPrice=$($price).html(); //take off $ indiPrice=indiPrice.substring(1) //make sure it is number format var aindiPrice=Number(indiPrice); //push into the array productIdPrice[id]=(aindiPrice); var url=update.php $.getJSON( url, {productId:tableId, //tableId is from the other jquery code which refers to qty:qty}, productId function(responseProduct){ $.each(responseProduct, function(productIndex, Qty){ //loop the return data if(productIdPrice[productIndex]){ //get the price from the previous array we create X Qty newSub=productIdPrice[productIndex]*Number(Qty); //productIdPrice[productIndex] are the price like 199.99 or 99.99 // Qty are Quantity like 9 or 10 or 3 sum+=newSub; newSub.toFixed(2); //try to solve the problem with toFixed but didn't work console.log("id: "+productIdPrice[productIndex]) console.log("Qty: "+Qty); console.log(newSub); **//newSub sometime become XXXX.96999999994** }; Thanks again!

    Read the article

  • Jquery Bugs?? Long decimal number after two numbers multiply...

    - by Jerry
    Hi all I am working on a shopping site and I am trying to calculate the subtotal of products. I got my price from a array and quantity from getJSON response array. Two of them multiply comes to my subtotal. I can change the quantity and it will comes out different subtotal. However,when I change the quantity to certain number, the final subtotal is like 259.99999999994 or some long decimal number. I use console.log to check the $price and $qty. Both of them are in the correct format ex..299.99 and 6 quantity.I have no idea what happen. I would appreciate it if someone can help me about it. Here is my Jquery code. $(".price").each(function(index, price){ $price=$(this); //get the product id and the price shown on the page var id=$price.closest('tr').attr('id'); var indiPrice=$($price).html(); //take off $ indiPrice=indiPrice.substring(1) //make sure it is number format var aindiPrice=Number(indiPrice); //push into the array productIdPrice[id]=(aindiPrice); var url=update.php $.getJSON( url, {productId:tableId, //tableId is from the other jquery code which refers to qty:qty}, productId function(responseProduct){ $.each(responseProduct, function(productIndex, Qty){ //loop the return data if(productIdPrice[productIndex]){ //get the price from the previous array we create X Qty newSub=productIdPrice[productIndex]*Number(Qty); //productIdPrice[productIndex] are the price like 199.99 or 99.99 // Qty are Quantity like 9 or 10 or 3 sum+=newSub; newSub.toFixed(2); //try to solve the problem with toFixed but didn't work console.log("id: "+productIdPrice[productIndex]) console.log("Qty: "+Qty); console.log(newSub); **//newSub sometime become XXXX.96999999994** }; Thanks again!

    Read the article

  • How to globalize ASP.NET MVC views (decimal separators in particular)?

    - by Pawel Krakowiak
    I'm working with the NerdDinner sample application and arrived at the section which deals with the Virtual Earth map. The application stores some values for the longitude and latitude. Unfortunately on my system floating point numbers are stored with a comma as the decimal separator, not a dot like in the US. So if I have a latitude of 47.64 it's retrieved and displayed as 47,64. Because that value is passed in a function call to the Virtual Earth API it fails at that point (e.g. JavaScript API expects 47.64, -122.13, but gets 47,64, -122,13). I need to make sure that the application always uses dots. In a WebForms app I would have a common class which overrides the System.Web.UI.Page.InitializeCulture() method and I would be inheriting my pages from that class. I am not sure about how to do the same with MVC. Do I need a customized ViewPage or something? Is there an easy way to solve this? Examples?

    Read the article

  • Not allow more than 5 digits after decimal. in on javascript "OnKeyUp"?

    - by James123
    I have a javascript code for textbox that will put commas on in digits like (11,23,233) mTextbox.Attributes.Add("OnKeyUp", "javascript:this.value=Comma(this.value);") function Comma(Num) { Num += ''; Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', ''); x = Num.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) x1 = x1.replace(rgx, '$1' + ',' + '$2'); return x1 + x2; } Now same here I need to restrict user to enter not morethan 5 digits after decimal (ex: Allow: 12,23,221.34323 Not Allow: 12,23,232.232423 I can change above javascript to work that?

    Read the article

  • Advice welcomed on creating my own Swing component

    - by Toto
    Recently I asked which was the best Swing component to bind to a BigDecimal variable (with some particular editing properties). It turns out that none of the standard Swing components suit me completely, nor did the third-party Swing component libraries I've found out there. So I’ve decided to create my own Swing component. Component description: I want to extend JTextField or JFormattedTextField, so my new component can be easily bound to a BigDecimal variable. The component will have customizable scale and length properties. Behavior: When the component is drawn, it shows only the decimal point and space for scale digits to its right. When the component receives focus the caret should be positioned left to the decimal point. As the user types numbers (any other character is ignored) they appear to the left of the caret, only length – scale numbers are accepted, any other number typed is ignored as the integer portion is full. Any time the user types the decimal point the caret moves to the right side of the decimal point. The following numbers typed are shown in the decimal part, only scale numbers are considered any other number typed is ignored as the decimal portion is full. Additionally, thousand separators should appear as the user types numbers left to the decimal point. Invoking a getValue() method on the component should yield the BigDecimal representing the number just entered. I’ve never created my own Swing component; I’ve barely used the standard ones. So I would appreciate any good tutorial/info/tip on creating the component described. This is the only thing I've got so far. Thanks in advance.

    Read the article

  • floating point hex octal binary

    - by workinprogress
    Hi, I am working on a calculator that allows you to perform calculations past the decimal point in octal, hexadecimal, binary, and of course decimal. I am having trouble though finding a way to convert floating point decimal numbers to floating point hexadecimal, octal, binary and vice versa. The plan is to do all the math in decimal and then convert the result into the appropriate number system. Any help, ideas or examples would be appreciated. Thanks!

    Read the article

  • polymorphism, inheritance in c# - base class calling overridden method?

    - by Andrew Johns
    This code doesn't work, but hopefully you'll get what I'm trying to achieve here. I've got a Money class, which I've taken from http://www.noticeablydifferent.com/CodeSamples/Money.aspx, and extended it a little to include currency conversion. The implementation for the actual conversion rate could be different in each project, so I decided to move the actual method for retrieving a conversion rate (GetCurrencyConversionRate) into a derived class, but the ConvertTo method contains code that would work for any implementation assuming the derived class has overriden GetCurrencyConversionRate so it made sense to me to keep it in the parent class? So what I'm trying to do is get an instance of SubMoney, and be able to call the .ConvertTo() method, which would in turn use the overriden GetCurrencyConversionRate, and return a new instance of SubMoney. The problem is, I'm not really understanding some concepts of polymorphism and inheritance yet, so not quite sure what I'm trying to do is even possible in the way I think it is, as what is currently happening is that I end up with an Exception where it has used the base GetCurrencyConversionRate method instead of the derived one. Something tells me I need to move the ConvertTo method down to the derived class, but this seems like I'll be duplicating code in multiple implementations, so surely there's a better way? public class Money { public CurrencyConversionRate { get { return GetCurrencyConversionRate(_regionInfo.ISOCurrencySymbol); } } public static decimal GetCurrencyConversionRate(string isoCurrencySymbol) { throw new Exception("Must override this method if you wish to use it."); } public Money ConvertTo(string cultureName) { // convert to base USD first by dividing current amount by it's exchange rate. Money someMoney = this; decimal conversionRate = this.CurrencyConversionRate; decimal convertedUSDAmount = Money.Divide(someMoney, conversionRate).Amount; // now convert to new currency CultureInfo cultureInfo = new CultureInfo(cultureName); RegionInfo regionInfo = new RegionInfo(cultureInfo.LCID); conversionRate = GetCurrencyConversionRate(regionInfo.ISOCurrencySymbol); decimal convertedAmount = convertedUSDAmount * conversionRate; Money convertedMoney = new Money(convertedAmount, cultureName); return convertedMoney; } } public class SubMoney { public SubMoney(decimal amount, string cultureName) : base(amount, cultureName) {} public static new decimal GetCurrencyConversionRate(string isoCurrencySymbol) { // This would get the conversion rate from some web or database source decimal result = new Decimal(2); return result; } }

    Read the article

  • Crystal Reports : How to add an external assembly class?

    - by Sunil
    I am using VS2010, CrystalReport13 & MVC3. My problem is unable to add an external assembly in Crystal Report using "Database Expert" Option. I have a class named WeeklyReportModel in an external assembly. In my web project, data retrieving from DB as IEnumerable collection of WeeklyReportModel. I tried ProjectData - .NetObjects in Crystal Report for adding the WeeklyReportModel. But this external assembly is not showing under ".NetObjects". Then I tried other option as Create New Connection - ADO.Net – Make New Connection and pointed this External Assembly. It has been added under Ado.Net node, but while expanding displays as "...no items found..." Totally frustrated. Please help. External Assembly Class: namespace SMS.Domain { public class WeeklyReportModel { public int StoreId { get; set; } public string StoreName{ get; set; } public decimal Saturday { get; set; } public decimal Sunday { get; set; } public decimal Monday { get; set; } public decimal Tuesday { get; set; } public decimal Wednesday { get; set; } public decimal Thurday { get; set; } public decimal Friday { get; set; } public decimal Average { get; set; } public string DateRange { get; set; } } } In Controller-action[Data retrieving as Collection Of WeeklyReportModel] namespace SMS.UI.Controllers { public class ReportController : Controller { public ActionResult StoreWeeklyReport(string id) { DateTime weekStart, weekClose; string[] dateArray = id.Split('_'); weekStart = Convert.ToDateTime(dateArray[0].ToString()); weekClose = Convert.ToDateTime(dateArray[1].ToString()); SMS.Infrastructure.Report.AuditReport weeklyReport = new SMS.Infrastructure.Report.AuditReport(); IEnumerable<SMS.Domain.WeeklyReportModel> weeklyRpt = weeklyReport.ReportByStore().WeeklyReport(weekStart, weekClose); Session["WeeklyData"] = weeklyRpt; Response.Redirect("~/Reports/Weekly/StoreWeekly.aspx"); return View(); } } } Thanks in advance.

    Read the article

  • Convert IDictionary to Dictionary

    - by croisharp
    I have to convert System.Collections.Generic.IDictionary<string, decimal> to System.Collections.Generic.Dictionary<string, decimal>, and i can't. I tried the ToDictionary method and can't specify right arguments. I've tried the following: // my dictionary is PlannedSurfaces (of type IDictionary<string, decimal>) blabla.ToDictionary<string, decimal>(localConstruction.PlannedSurfaces)

    Read the article

  • C# SQLite file import prevent duplicates

    - by jakesankey
    Hi, I am attempting to get a directory (which is ever-growing) full of .txt comma delimited files to import into my SQLite db. I now have all of the files importing ok, however I need to have some way of excluding the files that have been previously added to db. I have a column in the db called FileName where the name and extension are stored next to each record from each file. Now I need to say 'If the code finds XXX.txt and XXX.txt is already in db, then skip this file'. Can I somehow add this logic to the getfiles command or is there another easy way? using (SQLiteCommand insertCommand = con.CreateCommand()) { SQLiteCommand cmdd = con.CreateCommand(); string[] files = Directory.GetFiles(@"C:\Documents and Settings\js91162\Desktop\", "R303717*.txt*", SearchOption.AllDirectories); foreach (string file in files) { string FileNameExt1 = Path.GetFileName(file); cmdd.CommandText = @" SELECT COUNT(*) FROM Import WHERE FileName = @FileExt;"; cmdd.Parameters.Add(new SQLiteParameter("@FileExt", FileNameExt1)); int count = Convert.ToInt32(cmdd.ExecuteScalar()); //int count = ((IConvertible)insertCommand.ExecuteScalar().ToInt32(null)); if (count == 0) { Console.WriteLine("Parsing CMM data for SQL database... Please wait."); insertCommand.CommandText = @" INSERT INTO Import (FeatType, FeatName, Value, Actual, Nominal, Dev, TolMin, TolPlus, OutOfTol, PartNumber, CMMNumber, Date, FileName) VALUES (@FeatType, @FeatName, @Value, @Actual, @Nominal, @Dev, @TolMin, @TolPlus, @OutOfTol, @PartNumber, @CMMNumber, @Date, @FileName);"; insertCommand.Parameters.Add(new SQLiteParameter("@FeatType", DbType.String)); insertCommand.Parameters.Add(new SQLiteParameter("@FeatName", DbType.String)); insertCommand.Parameters.Add(new SQLiteParameter("@Value", DbType.String)); insertCommand.Parameters.Add(new SQLiteParameter("@Actual", DbType.Decimal)); insertCommand.Parameters.Add(new SQLiteParameter("@Nominal", DbType.Decimal)); insertCommand.Parameters.Add(new SQLiteParameter("@Dev", DbType.Decimal)); insertCommand.Parameters.Add(new SQLiteParameter("@TolMin", DbType.Decimal)); insertCommand.Parameters.Add(new SQLiteParameter("@TolPlus", DbType.Decimal)); insertCommand.Parameters.Add(new SQLiteParameter("@OutOfTol", DbType.Decimal)); insertCommand.Parameters.Add(new SQLiteParameter("@Comment", DbType.String)); string FileNameExt = Path.GetFileName(file); string RNumber = Path.GetFileNameWithoutExtension(file); string RNumberE = RNumber.Split('_')[0]; string RNumberD = RNumber.Split('_')[1]; string RNumberDate = RNumber.Split('_')[2]; DateTime dateTime = DateTime.ParseExact(RNumberDate, "yyyyMMdd", Thread.CurrentThread.CurrentCulture); string cmmDate = dateTime.ToString("dd-MMM-yyyy"); string[] lines = File.ReadAllLines(file); bool parse = false; foreach (string tmpLine in lines) { string line = tmpLine.Trim(); if (!parse && line.StartsWith("Feat. Type,")) { parse = true; continue; } if (!parse || string.IsNullOrEmpty(line)) { continue; } Console.WriteLine(tmpLine); foreach (SQLiteParameter parameter in insertCommand.Parameters) { parameter.Value = null; } string[] values = line.Split(new[] { ',' }); for (int i = 0; i < values.Length - 1; i++) { SQLiteParameter param = insertCommand.Parameters[i]; if (param.DbType == DbType.Decimal) { decimal value; param.Value = decimal.TryParse(values[i], out value) ? value : 0; } else { param.Value = values[i]; } } insertCommand.Parameters.Add(new SQLiteParameter("@PartNumber", RNumberE)); insertCommand.Parameters.Add(new SQLiteParameter("@CMMNumber", RNumberD)); insertCommand.Parameters.Add(new SQLiteParameter("@Date", cmmDate)); insertCommand.Parameters.Add(new SQLiteParameter("@FileName", FileNameExt)); // insertCommand.ExecuteNonQuery(); } } } Console.WriteLine("CMM data successfully imported to SQL database..."); } con.Close(); }

    Read the article

  • Code contracts and inheritance

    - by DigiMortal
    In my last posting about code contracts I introduced you how to force code contracts to classes through interfaces. In this posting I will go step further and I will show you how code contracts work in the case of inherited classes. As a first thing let’s take a look at my interface and code contracts. [ContractClass(typeof(ProductContracts))] public interface IProduct {     int Id { get; set; }     string Name { get; set; }     decimal Weight { get; set; }     decimal Price { get; set; } }   [ContractClassFor(typeof(IProduct))] internal sealed class ProductContracts : IProduct {     private ProductContracts() { }       int IProduct.Id     {         get         {             return default(int);         }         set         {             Contract.Requires(value > 0);         }     }       string IProduct.Name     {         get         {             return default(string);         }         set         {             Contract.Requires(!string.IsNullOrWhiteSpace(value));             Contract.Requires(value.Length <= 25);         }     }       decimal IProduct.Weight     {         get         {             return default(decimal);         }         set         {             Contract.Requires(value > 3);             Contract.Requires(value < 100);         }     }       decimal IProduct.Price     {         get         {             return default(decimal);         }         set         {             Contract.Requires(value > 0);             Contract.Requires(value < 100);         }     } } And here is the product class that inherits IProduct interface. public class Product : IProduct {     public int Id { get; set; }     public string Name { get; set; }     public virtual decimal Weight { get; set; }     public decimal Price { get; set; } } if we run this code and violate the code contract set to Id we will get ContractException. public class Program {     static void Main(string[] args)     {         var product = new Product();         product.Id = -100;     } }   Now let’s make Product to be abstract class and let’s define new class called Food that adds one more contract to Weight property. public class Food : Product {     public override decimal Weight     {         get         {             return base.Weight;         }         set         {             Contract.Requires(value > 1);             Contract.Requires(value < 10);               base.Weight = value;         }     } } Now we should have the following rules at place for Food: weight must be greater than 1, weight must be greater than 3, weight must be less than 100, weight must be less than 10. Interesting part is what happens when we try to violate the lower and upper limits of Food weight. To see what happens let’s try to violate rules #2 and #4. Just comment one of the last lines out in the following method to test another assignment. public class Program {     static void Main(string[] args)     {         var food = new Food();         food.Weight = 12;         food.Weight = 2;     } } And here are the results as pictures to see where exceptions are thrown. Click on images to see them at original size. Violation of lower limit. Violation of upper limit. As you can see for both violations we get ContractException like expected. Code contracts inheritance is powerful and at same time dangerous feature. Although you can always narrow down the conditions that come from more general classes it is possible to define impossible or conflicting contracts at different points in inheritance hierarchy.

    Read the article

  • Working with packed dates in SSIS

    - by Jim Giercyk
    One of the challenges recently thrown my way was to read an EBCDIC flat file, decode packed dates, and insert the dates into a SQL table.  For those unfamiliar with packed data, it is a way to store data at the nibble level (half a byte), and was often used by mainframe programmers to conserve storage space.  In the case of my input file, the dates were 2 bytes long and  represented the number of days that have past since 01/01/1950.  My first thought was, in the words of Scooby, Hmmmmph?  But, I love a good challenge, so I dove in. Reading in the flat file was rather simple.  The only difference between reading an EBCDIC and an ASCII file is the Code Page option in the connection manager.  In my case, I needed to use Code Page 1140 for EBCDIC (I could have also used Code Page 37).       Once the code page is set correctly, SSIS can understand what it is reading and it will convert the output to the default code page, 1252.  However, packed data is either unreadable or produces non-alphabetic characters, as we can see in the preview window.   Column 1 is actually the packed date, columns 0 and 2 are the values in the rest of the file.  We are only interested in Column 1, which is a 2 byte field representing a packed date.  We know that 2 bytes of packed data can be stored in 1 byte of character data, so we are working with 4 packed digits in 2 character bytes.  If you are confused, stay tuned….this will make sense in a minute.   Right-click on your Flat File Source shape and select “Show Advanced Editor”. Here is where the magic begins. By changing the properties of the output columns, we can access the packed digits from each byte. By default, the Output Column data type is DT_STR. Since we want to look at the bytes individually and not the entire string, change the data type to DT_BYTES. Next, and most important, set UseBinaryFormat to TRUE. This will write the HEX VALUES of the output string instead of writing the character values.  Now we are getting somewhere! Next, you will need to use a Data Conversion shape in your Data Flow to transform the 2 position byte stream to a 4 position Unicode string containing the packed data.  You need the string to be 4 bytes long because it will contain the 4 packed digits.  Here is what that should look like in the Data Conversion shape: Direct the output of your data flow to a test table or file to see the results.  In my case, I created a test table.  The results looked like this:     Hold on a second!  That doesn't look like a date at all.  No, of course not.  It is a hex number which represents the days which have passed between 01/01/1950 and the date.  We have to convert the Hex value to a decimal value, and use the DATEADD function to get a date value.  Luckily, I have created a function to convert Hex to Decimal:   -- ============================================= -- Author:        Jim Giercyk -- Create date: March, 2012 -- Description:    Converts a Hex string to a decimal value -- ============================================= CREATE FUNCTION [dbo].[ftn_HexToDec] (     @hexValue NVARCHAR(6) ) RETURNS DECIMAL AS BEGIN     -- Declare the return variable here DECLARE @decValue DECIMAL IF @hexValue LIKE '0x%' SET @hexValue = SUBSTRING(@hexValue,3,4) DECLARE @decTab TABLE ( decPos1 VARCHAR(2), decPos2 VARCHAR(2), decPos3 VARCHAR(2), decPos4 VARCHAR(2) ) DECLARE @pos1 VARCHAR(1) = SUBSTRING(@hexValue,1,1) DECLARE @pos2 VARCHAR(1) = SUBSTRING(@hexValue,2,1) DECLARE @pos3 VARCHAR(1) = SUBSTRING(@hexValue,3,1) DECLARE @pos4 VARCHAR(1) = SUBSTRING(@hexValue,4,1) INSERT @decTab VALUES (CASE               WHEN @pos1 = 'A' THEN '10'                 WHEN @pos1 = 'B' THEN '11'               WHEN @pos1 = 'C' THEN '12'               WHEN @pos1 = 'D' THEN '13'               WHEN @pos1 = 'E' THEN '14'               WHEN @pos1 = 'F' THEN '15'               ELSE @pos1              END, CASE               WHEN @pos2 = 'A' THEN '10'                 WHEN @pos2 = 'B' THEN '11'               WHEN @pos2 = 'C' THEN '12'               WHEN @pos2 = 'D' THEN '13'               WHEN @pos2 = 'E' THEN '14'               WHEN @pos2 = 'F' THEN '15'               ELSE @pos2              END, CASE               WHEN @pos3 = 'A' THEN '10'                 WHEN @pos3 = 'B' THEN '11'               WHEN @pos3 = 'C' THEN '12'               WHEN @pos3 = 'D' THEN '13'               WHEN @pos3 = 'E' THEN '14'               WHEN @pos3 = 'F' THEN '15'               ELSE @pos3              END, CASE               WHEN @pos4 = 'A' THEN '10'                 WHEN @pos4 = 'B' THEN '11'               WHEN @pos4 = 'C' THEN '12'               WHEN @pos4 = 'D' THEN '13'               WHEN @pos4 = 'E' THEN '14'               WHEN @pos4 = 'F' THEN '15'               ELSE @pos4              END) SET @decValue = (CONVERT(INT,(SELECT decPos4 FROM @decTab)))         +                 (CONVERT(INT,(SELECT decPos3 FROM @decTab))*16)      +                 (CONVERT(INT,(SELECT decPos2 FROM @decTab))*(16*16)) +                 (CONVERT(INT,(SELECT decPos1 FROM @decTab))*(16*16*16))     RETURN @decValue END GO     Making use of the function, I found the decimal conversion, added that number of days to 01/01/1950 and FINALLY arrived at my “unpacked relative date”.  Here is the query I used to retrieve the formatted date, and the result set which was returned: SELECT [packedDate] AS 'Hex Value',        dbo.ftn_HexToDec([packedDate]) AS 'Decimal Value',        CONVERT(DATE,DATEADD(day,dbo.ftn_HexToDec([packedDate]),'01/01/1950'),101) AS 'Relative String Date'   FROM [dbo].[Output Table]         This technique can be used any time you need to retrieve the hex value of a character string in SSIS.  The date example may be a bit difficult to understand at first, but with SSIS becoming the preferred tool for enterprise level integration for many companies, there is no doubt that developers will encounter these types of requirements with regularity in the future. Please feel free to contact me if you have any questions.

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >