|
Answered here[^].
..and now you know "why" it is not done.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
|
Again, you're putting spaces and special characters in the parameter names.
DO NOT USE SPACES AND SPECIAL CHARACTERS IN TABLE NAMES, FIELD NAMES AND PARAMETER NAMES!
Your field names should be something like this:
Name, Age, Class, Gender, GuardianName, ContactPhone, Address, EmailAddress
By making the code more "eyeball friendly" to read, you are giving yourself headaches debugging the resulting code. "Eyeball friendly" is NOT "compiler friendly"!
|
|
|
|
|
Clean-up crew needed, grammar spill... - Nagy Vilmos
|
|
|
|
|
Hi,
I am using MySQL database in my C# .NET application and saving all dates in the database as UTC_TIMESTAMP
I want to know to display it for the user in his own local time according to his Microsoft Windows?
Thanks,
Jassim
Technology News @ www.JassimRahma.com
|
|
|
|
|
Try reading the documentation on the DateTime structure, here[^].
Dim databaseUtcTime = dateTimeFromDatabase
databaseUtcTime = databaseUtcTime.SpecifyKind(DateTimeKind.Utc)
Debug.WriteLine(String.Format("UtcTime: {0}", databaseUtcTime.ToString()))
Debug.WriteLine(String.Format("LocalTime: {0}", databaseUtcTime.ToLocalTime().ToString()))
|
|
|
|
|
Alright, this is not exactly a programming question, but I also doubt that it would fit into the Lounge.
Situation: I am currently implementing the Syslog Protocol in .Net, starting with the Base classes (Message, Header, Struct. Data). The Header contains a timestamp which's formatting is exactly defined.
A timestamp may look as follows:
2014-2-4T14:22:56.235Z+1
2014-2-4T14:22:56.235Z-1.5
2014-2-4T14:22:56.235123Z+1
What I have done so far is that I consider System.DateTime being unuseable as timestamp, even with a wrapper around it it would be highly difficult since setting a single field (e.g. Day, Year, Month and so on) is only possible by parsing an entire time string, or adding a Time span.
Now to avoid these circumstances, I have implemented the following class SyslogTimestamp:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Springlog.Com.Messaging
{
public class SyslogTimestamp
{
#region Properties
static short GetDayMaxDaysOfMonth(int month, int year)
{
if (month != 2)
{
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
{
return 31;
}
else
{
return 30;
}
}
else
{
if (IsLeapYear(year))
{
return 29;
}
return 28;
}
}
private static bool IsLeapYear(int year)
{
if (year % 4 == 0)
{
if (year % 100 == 0)
{
if (year % 400 == 0)
{
return true;
}
return false;
}
return true;
}
return false;
}
int year;
public int Year
{
get { return year; }
}
int month;
public int Month
{
get { return month; }
}
int dayOfMonth;
public int DayOfMonth
{
get { return dayOfMonth; }
}
int hours;
public int Hours
{
get { return hours; }
}
int minutes;
public int Minutes
{
get { return minutes; }
}
int seconds;
public int Seconds
{
get { return seconds; }
}
int miliseconds;
public int Miliseconds
{
get { return miliseconds; }
}
double utcOffset;
public double UtcOffset
{
get { return utcOffset; }
set { utcOffset = value; }
}
#endregion
public SyslogTimestamp()
{
Reset();
}
public SyslogTimestamp(string timestamp)
{
Reset();
FromString(timestamp);
}
public SyslogTimestamp(DateTime timestamp)
{
Reset();
FromDateTime(timestamp);
}
private void Reset()
{
miliseconds = 0;
seconds = 0;
minutes = 0;
hours = 0;
dayOfMonth = 0;
month = 1;
year = 1;
utcOffset = 0;
}
public bool FromString(string dateTime)
{
Regex splitRegex = new Regex("([0-9]{4})-([1-9]|[1][0-2])-([0-2]?[0-9]|[3][0-1])[T]([0-1]?[0-9]|[2][0-3])[:]([0-5]?[0-9])[:]([0-5]?[0-9])?.?([0-9]{1,6})[Z]([+-][0-9]|[+-]?[0][1][0-2])", RegexOptions.IgnoreCase);
Match timestamp = splitRegex.Match(dateTime);
if (timestamp.Groups.Count == 9)
{
AddYears(Int32.Parse(timestamp.Groups[1].Value));
AddMonths(Int32.Parse(timestamp.Groups[2].Value));
AddDays(Int32.Parse(timestamp.Groups[3].Value));
AddHours(Int32.Parse(timestamp.Groups[4].Value));
AddMinutes(Int32.Parse(timestamp.Groups[5].Value));
AddSeconds(Int32.Parse(timestamp.Groups[6].Value));
AddMilliseconds(Int32.Parse(timestamp.Groups[7].Value));
utcOffset = Int32.Parse(timestamp.Groups[8].Value);
return true;
}
else
{
return false;
}
}
public string ToFormattedString()
{
string timezonPreSign = "+";
if (utcOffset < 0)
{
timezonPreSign = "";
}
return string.Format("{0}-{1}-{2}T{3}:{4}:{5}.{6}Z{7}{8}", year, month, dayOfMonth, hours, minutes, seconds, miliseconds, timezonPreSign, utcOffset);
}
public override string ToString()
{
return this.ToFormattedString();
}
public void FromDateTime(DateTime timestamp, bool convertToUtc = true)
{
TimeSpan utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(timestamp);
if (convertToUtc)
{
timestamp.Add(utcOffset);
this.utcOffset = 0;
}
else
{
this.utcOffset = utcOffset.Hours + (utcOffset.Minutes / 100);
}
AddMilliseconds(timestamp.Millisecond);
AddSeconds(timestamp.Second);
AddMinutes(timestamp.Minute);
AddHours(timestamp.Hour);
AddDays(timestamp.Day);
AddMonths(timestamp.Month);
AddYears(timestamp.Year);
}
public void Add(TimeSpan timeSpan)
{
AddMilliseconds(timeSpan.Milliseconds);
AddSeconds(timeSpan.Seconds);
AddMinutes(timeSpan.Minutes);
AddHours(timeSpan.Hours);
AddDays(timeSpan.Days);
}
public void AddMilliseconds(int val)
{
if (val + miliseconds >= 1000)
{
AddSeconds( val / 1000);
miliseconds = (val % 1000);
}
else
{
miliseconds += val;
}
}
private void AddSeconds(int val)
{
if (seconds + val >= 60)
{
AddMinutes(val / 60);
seconds = (val % 60);
}
else
{
seconds += val;
}
}
private void AddMinutes(int val)
{
if (minutes + val >= 60)
{
AddMinutes(val / 60);
minutes = (val % 60);
}
else
{
minutes += val;
}
}
private void AddHours(int val)
{
if (minutes + val >= 24)
{
AddDays (val / 24);
minutes = (val % 24);
}
else
{
minutes += val;
}
}
private void AddDays(int val)
{
short dayCount = GetDayMaxDaysOfMonth(month, year);
if (dayOfMonth + val > dayCount)
{
AddMonths(val / dayCount);
dayOfMonth = (val % dayCount);
}
else
{
dayOfMonth += val;
}
}
private void AddMonths(int val)
{
if (month + val > 12)
{
AddYears(val / 12);
month = (val % 12);
}
else
{
month += val;
}
}
private void AddYears(int val)
{
year += val;
}
public override bool Equals(object o)
{
if (o is SyslogTimestamp)
{
return DoMatch((SyslogTimestamp)o, this);
}
else
{
return false;
}
}
public static bool DoMatch(SyslogTimestamp a, SyslogTimestamp b)
{
bool doMatch = (a.year == b.Year)
&& (a.month == b.Month)
&& (a.dayOfMonth == b.DayOfMonth)
&& (a.hours == b.Hours)
&& (a.minutes == b.Minutes)
&& (a.seconds == b.Seconds)
&& (a.miliseconds == b.Miliseconds)
&& (a.utcOffset == b.UtcOffset);
return doMatch;
}
public static bool operator ==(SyslogTimestamp a, SyslogTimestamp b)
{
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
if (((object)a == null) || ((object)b == null))
{
return false;
}
return DoMatch(a, b);
}
public static bool operator !=(SyslogTimestamp a, SyslogTimestamp b)
{
return !(a == b);
}
public static bool operator <(SyslogTimestamp a, SyslogTimestamp b)
{
if (a.Year < b.Year) { return true; }
if (a.Year > b.Year) { return false; }
if (a.Month < b.Month) { return true; }
if (a.Month > b.Month) { return false; }
if (a.DayOfMonth < b.DayOfMonth) { return true; }
if (a.DayOfMonth > b.DayOfMonth) { return false; }
if ((a.Hours + a.UtcOffset) < (b.Hours + b.UtcOffset)) { return true; }
if ((a.Hours + a.UtcOffset) > (b.Hours + b.UtcOffset)) { return false; }
if (a.Minutes < b.Minutes) { return true; }
if (a.Minutes > b.Minutes) { return false; }
if (a.Seconds < b.Seconds) { return true; }
if (a.Seconds > b.Seconds) { return false; }
if (a.Miliseconds < b.Miliseconds) { return true; }
if (a.Miliseconds > b.Miliseconds) { return false; }
return false;
}
public static bool operator >(SyslogTimestamp a, SyslogTimestamp b)
{
if (a.Year > b.Year) { return true; }
if (a.Year < b.Year) { return false; }
if (a.Month > b.Month) { return true; }
if (a.Month < b.Month) { return false; }
if (a.DayOfMonth > b.DayOfMonth) { return true; }
if (a.DayOfMonth < b.DayOfMonth) { return false; }
if ((a.Hours + a.UtcOffset) > (b.Hours + b.UtcOffset)) { return true; }
if ((a.Hours + a.UtcOffset) < (b.Hours + b.UtcOffset)) { return false; }
if (a.Minutes > b.Minutes) { return true; }
if (a.Minutes < b.Minutes) { return false; }
if (a.Seconds > b.Seconds) { return true; }
if (a.Seconds < b.Seconds) { return false; }
if (a.Miliseconds > b.Miliseconds) { return true; }
if (a.Miliseconds < b.Miliseconds) { return false; }
return false;
}
public static bool operator >=(SyslogTimestamp a, SyslogTimestamp b)
{
return (a > b) || DoMatch(a, b);
}
public static bool operator <=(SyslogTimestamp a, SyslogTimestamp b)
{
return (a < b) || DoMatch(a, b);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}
Of course I have Unit Tests to check the integrity of the data handling within that class:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Springlog.Com.Messaging;
namespace Springlog.Com.Messaging.UnitTests
{
[TestClass]
public class SyslogTimestampUnitTest
{
[TestMethod]
public void SyslogTimestampComparisonIntegrity()
{
SyslogTimestamp timestamp1 = new SyslogTimestamp();
SyslogTimestamp timestamp2 = new SyslogTimestamp();
SyslogTimestamp timestamp3 = new SyslogTimestamp();
SyslogTimestamp timestamp4 = new SyslogTimestamp();
timestamp1.FromDateTime(DateTime.Now);
timestamp2.FromDateTime(DateTime.Now.AddDays(-1));
timestamp3 = timestamp1;
timestamp4.FromDateTime(DateTime.Now.AddMinutes(2));
Assert.AreEqual(true, (timestamp1 > timestamp2));
Assert.AreEqual(true, (timestamp4 > timestamp1));
Assert.AreEqual(false, (timestamp1 < timestamp2));
Assert.AreEqual(true, (timestamp1 >= timestamp2));
Assert.AreEqual(false, (timestamp1 <= timestamp2));
Assert.AreEqual(true, (timestamp1 == timestamp3));
Assert.AreEqual(false, (timestamp1 != timestamp3));
Assert.AreEqual(false, (timestamp1 == timestamp4));
Assert.AreEqual(false, (timestamp1 == timestamp2));
}
[TestMethod]
public void SyslogTimestampStringConversionIntegrity()
{
DateTime now = DateTime.Now;
SyslogTimestamp timestamp = new SyslogTimestamp();
SyslogTimestamp timestamp2 = new SyslogTimestamp();
timestamp.FromDateTime(now);
timestamp.UtcOffset = 1;
Assert.AreEqual(true, timestamp2.FromString(timestamp.ToFormattedString()));
Assert.AreEqual(true, (timestamp2 == timestamp));
}
}
}
Now my question is: Can I achieve the same with System.DateTime?
I seriously doubt that, since System.DateTime's ParseExact method tends to have problems dealing with a variable amount of microseconds, and does not provide any field to store the UTC Offset.
Edit: I provided the new class implementation, since I have added various improvements.
Clean-up crew needed, grammar spill... - Nagy Vilmos
modified 5-Feb-14 8:52am.
|
|
|
|
|
personally I would never re-write it. I once tried and though it was more than a reasonable effort, the amount of rules and things to think of becomes very large and does not outwheigh the disadvantages of being stuck with the standard DateTime.
([SMALL RANT]And I'm now working with Java's GregorianCalendar, how I wish I had a DateTime object [/SMALL RANT])
Marco Bertschi wrote: since System.DateTime's ParseExact method tends to have problems dealing with a variable amount of microseconds, and does not provide any field to store the UTC Offset.
Variable microseconds can be handled with a few lines of business logic I think and for the UTC Offset you could create a new DateTime Object that inherits from the DateTime class? (just a quick thought)
good luck.
|
|
|
|
|
V. wrote: Variable microseconds can be handled with a few lines of business logic I think
The big deal is that the Syslog Timestamp has special characters in it, in order to make it better parseable. ParseExact can't handle them properly, somehow.
V. wrote: for the UTC Offset you could create a new DateTime Object that inherits from the DateTime class? (just a quick thought)
And then I'd end up with what I already have, since the UTC Offset must be recognized when comparing two types of the new datetime class.
In the end I'd say that it is a reasonable amount of work, especially since Date/Time stuff isn't going to change too soon, and if it has proven itself worth the work it will last longer than both of us will ever live.
Clean-up crew needed, grammar spill... - Nagy Vilmos
|
|
|
|
|
DateTime is a sealed class, so you can't inherit from it.
“But I don't want to go among mad people,” Alice remarked.
“Oh, you can't help that,” said the Cat: “we're all mad here. I'm mad. You're mad.”
“How do you know I'm mad?” said Alice.
“You must be," said the Cat, or you wouldn't have come here.” Lewis Carroll
|
|
|
|
|
[Edit]
Crap. I saw "Timestamp" read it "Timespan".
Actually, I was right. DateTime structure[^]. I'll get the right eventually!
|
|
|
|
|
Marco Bertschi wrote: Can I achieve the same with System.DateTime? Based on the observation that all of your Properties, except milliseconds, are 'get only, I would say "yes," if you were willing to accept the limitations of inheriting from a data-structure like a Tuple<T1,T2,T3> ... given the fact that Tuple instances are immutable.
I don't claim to have thought through your use scenario here in any great depth, or to fully understand your goals here, but here's a quick sketch:
using System;
namespace Feb4_2014_InheritFromTupleT1T2T3
{
public class DateTimeEx: Tuple<DateTime, long, Int32>
{
private const string msPrefix = ":Z";
private const string tzPlus = "+";
private string tzPre;
public DateTime dateTime { set; get; }
public long milliSeconds { set; get; }
public Int32 utcOffset { set; get; }
public DateTimeEx(DateTime datetime, long millisec, Int32 utcoff) : base(datetime, millisec, utcoff)
{
dateTime = datetime;
milliSeconds = millisec;
utcOffset = utcoff;
}
public override string ToString()
{
tzPre = (milliSeconds < 0) ? "" : tzPlus;
return string.Format("{0}-{1}-{2}T{3}:{4}:{5}.{6}Z{7}{8}", Item1.Year, Item1.Month, Item1.Day, Item1.Hour, Item1.Minute, Item1.Second, milliSeconds, tzPre, utcOffset);
}
}
} Here's the results of a simple test:
DateTime rightNow = DateTime.Now;
DateTimeEx dEx1 = new DateTimeEx(rightNow, 0, 7);
DateTimeEx dEx2 = new DateTimeEx(rightNow, 0, 7);
DateTimeEx dEx3 = new DateTimeEx(rightNow, 230, 4);
Console.WriteLine(dEx1);
Console.WriteLine(dEx3);
Console.WriteLine(dEx1.Equals(dEx2));
Console.WriteLine(dEx1.Equals(dEx3)); I would hope what you would get from this is being able to use Parse, and ParseExact on the DateTime component, and, hopefully, save you from writing some of the overloads. But, whether you could use in the context of whatever your doing with SysLog: I ain't got a clue.
Hope this is helpful.
“But I don't want to go among mad people,” Alice remarked.
“Oh, you can't help that,” said the Cat: “we're all mad here. I'm mad. You're mad.”
“How do you know I'm mad?” said Alice.
“You must be," said the Cat, or you wouldn't have come here.” Lewis Carroll
|
|
|
|
|
BillWoodruff wrote: Based on the observation that all of your Properties, except milliseconds, are 'get only, I would say "yes," if you were willing to accept the limitations of inheriting from a data-structure like a Tuple<T1,T2,T3> ... given the fact that Tuple instances are immutable.
The read-only behavior will change soon, I only have to implement the value validation first.
BillWoodruff wrote: would hope what you would get from this is being able to use Parse, and ParseExact on the DateTime component,
I will almost certainly not be able to, since the UTC-Offset at the end (after the "Z") can't be handled by these functions. An overload may make sense, but will eventually end up in a big mess with the comparison operators.
I did some thinking myself in the meantime, and I consider an overloading of DateTime bein highly unusable, especially since DateTime has to present a Date/Time pair which may change, and a Timestamp has to represent a single Date/Time/UTC-Offset pair which is not going to change after its initialization (Apart from the problems of inheriting a struct which you already have mentioned).
Clean-up crew needed, grammar spill... - Nagy Vilmos
|
|
|
|
|
Marco Bertschi wrote: What I have done so far is that I consider System.DateTime being unuseable as timestamp,
You have effectively two 'layers' which needs a 'translation' layer in between.
That doesn't require a new timestamp class. What it requires is that you create functionality that parses (and formats if needed) and that goes in your translation layer. On the C# (application side) the input/output is a DateTime. On the syslog interface side it is a string.
|
|
|
|
|
jschell wrote: On the C# (application side) the input/output is a DateTime.
Yes, that's why the new class has a "FromDateTime(DateTime dateTime)"-Method.
jschell wrote: On the syslog interface side it is a string.
I am the one who provides the classes to serialize/deserialze the Syslog message, therefore a class might be useful, especially afterwards when showing the messages in the Logviewer (Ordering them by a timestamp type has almost certainly advantages over ordering them by a string which represents a timestamp).
I might be wrong in some point here (or I may not). I'll just go ahead and see what I'll learn. It's a side project which I do in my free time, so I am allowed to spend time making errors (and learning from them).
Clean-up crew needed, grammar spill... - Nagy Vilmos
|
|
|
|
|
Marco,
In your lounge post[^] you say that you imposing RFC5424[^] as the criteria. Based on the following format that I found online, you will not be able to properly store a RFC5424 timestamp in a DateTime structure due to the possibility of the TIME-SECFRAC being allowed to have up six digits. The DateTime structure can only accommodate milliseconds (3 digits).
Quote: TIMESTAMP = NILVALUE / FULL-DATE "T" FULL-TIME
FULL-DATE = DATE-FULLYEAR "-" DATE-MONTH "-" DATE-MDAY
DATE-FULLYEAR = 4DIGIT
DATE-MONTH = 2DIGIT ; 01-12
DATE-MDAY = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on
; month/year
FULL-TIME = PARTIAL-TIME TIME-OFFSET
PARTIAL-TIME = TIME-HOUR ":" TIME-MINUTE ":" TIME-SECOND
[TIME-SECFRAC]
TIME-HOUR = 2DIGIT ; 00-23
TIME-MINUTE = 2DIGIT ; 00-59
TIME-SECOND = 2DIGIT ; 00-59
TIME-SECFRAC = "." 1*6DIGIT
TIME-OFFSET = "Z" / TIME-NUMOFFSET
TIME-NUMOFFSET = ("+" / "-") TIME-HOUR ":" TIME-MINUTE You also have shown TimeStamp examples[^] that you say are valid. However these have decimal TIME-NUMOFFSET values instead of "Hours:Minutes"; again this conflicts with the specification. Is it your intent to allow these deviations?
Just courious, is there a reason that you have implemented your own GetDayMaxDaysOfMonth and Is LeapYear versus using those from the DateTimeStructure (DateTime.DaysInMonth[^], DateTime.IsLeapYear[^])?
|
|
|
|
|
TnTinMn wrote: In your lounge post[^] you say that you imposing RFC5424[^] as the criteria. Based on the following format that I found online, you will not be able to properly store a RFC5424 timestamp in a DateTime structure due to the possibility of the TIME-SECFRAC being allowed to have up six digits. The DateTime structure can only accommodate milliseconds (3 digits).
Thank you
TnTinMn wrote: You also have shown TimeStamp examples[^] that you say are valid. However these have decimal TIME-NUMOFFSET values instead of "Hours:Minutes"; again this conflicts with the specification. Is it your intent to allow these deviations?
I know that these are not valid examples, brain was off while typing
TnTinMn wrote: Just courious, is there a reason that you have implemented your own GetDayMaxDaysOfMonth and Is LeapYear versus using those from the DateTimeStructure (DateTime.DaysInMonth[^], DateTime.IsLeapYear[^])?
Pssst - I simply forgot about those
On the other hand side I didn't really bothered to check for something existing, since I had to learn the leap year rules anyways.
Clean-up crew needed, grammar spill... - Nagy Vilmos
|
|
|
|
|
Marco,
My statement "The DateTime structure can only accommodate milliseconds (3 digits)" was incorrect. Sorry about that.
You can access higher resolution through the usage of the Ticks property that has a 100 nanosecond resolution[^].
You could use DateTime.TryParseExact with this format string: "yyyy-MM-dd\THH:mm:ss"
If that succeeds then, then you would need to extract the fractional second component (if it exists) as microseconds (upto 6 digits) and convert the microseconds to Ticks. Then you you can use the DateTime.AddTicks method on the DateTime value returned from the TryParseExact method.
I have put together a class to parse a TimeStamp string using this methodolgy and can make a copy of the code available if you are interested in it.
Yeah, its cold and I saw this as an interesting exercise.
|
|
|
|
|
TnTinMn wrote: You could use DateTime.TryParseExact with this format string: "yyyy-MM-dd\THH:mm:ss"
If that succeeds then, then you would need to extract the fractional second component (if it exists) as microseconds (upto 6 digits) and convert the microseconds to Ticks. Then you you can use the DateTime.AddTicks method on the DateTime value returned from the TryParseExact method.
Which is very difficult.
The biggest problem starts when you try to parse the Miliseconds directly, as in DateTime.TryParseExact(yyyy-MM-dd\THH:mm:ss.fff) where fff defines the miliseconds. DateTime can't handle any conversion if the amount of 'f' is not equal to the amount of the miliseconds, e.g.
parsing 2014-02-13\15:33:12.12 with DateTime.TryParseExact(yyyy-MM-dd\HH:mm:ss.fff) would return false, which is a crucial problem in my case since the amount of miliseconds may differ between 0 and 100000.
Of course I could populate them prior to the conversion, but then I am better of with my own class where I have full control over the conversion.
TnTinMn wrote: I have put together a class to parse a TimeStamp string using this methodolgy and can make a copy of the code available if you are interested in it.
If you have it I'd love to see it. I have developed my own timestamp class a little further, here it is in case you are interested in it:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Springlog.Com.Messaging
{
public class SyslogTimestamp
{
#region Properties
static short GetDayMaxDaysOfMonth(int month, int year)
{
if (month != 2)
{
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
{
return 31;
}
else
{
return 30;
}
}
else
{
if (IsLeapYear(year))
{
return 29;
}
return 28;
}
}
private static bool IsLeapYear(int year)
{
if (year % 4 == 0)
{
if (year % 100 == 0)
{
if (year % 400 == 0)
{
return true;
}
return false;
}
return true;
}
return false;
}
int year;
public int Year
{
get { return year; }
}
int month;
public int Month
{
get { return month; }
}
int dayOfMonth;
public int DayOfMonth
{
get { return dayOfMonth; }
}
int hours;
public int Hours
{
get { return hours; }
}
int minutes;
public int Minutes
{
get { return minutes; }
}
int seconds;
public int Seconds
{
get { return seconds; }
}
int miliseconds;
public int Miliseconds
{
get { return miliseconds; }
}
double utcOffset;
public double UtcOffset
{
get { return utcOffset; }
set { utcOffset = value; }
}
#endregion
public SyslogTimestamp()
{
Reset();
}
public SyslogTimestamp(string timestamp)
{
Reset();
FromString(timestamp);
}
public SyslogTimestamp(DateTime timestamp)
{
Reset();
FromDateTime(timestamp);
}
private void Reset()
{
miliseconds = 0;
seconds = 0;
minutes = 0;
hours = 0;
dayOfMonth = 0;
month = 0;
year = 0;
utcOffset = 0;
}
public bool FromString(string dateTime)
{
Reset();
Regex splitRegex = new Regex(@"(\d{4})-(0?[1-9]|1[0-2])-([0-2]?\d|3[0-1])T?([0-1]?\d|2[0-3]):([0-5]?\d):([0-5]?\d)\.?(\d{0,6})?Z?([+-]?\d\.?\d?|\d{2}?|[0]?1[0-2]\.?\d?|\d{2}?)?", RegexOptions.IgnoreCase);
Match timestamp = splitRegex.Match(dateTime);
if (timestamp.Groups.Count == 9)
{
AddYears(Int32.Parse(timestamp.Groups[1].Value));
AddMonths(Int32.Parse(timestamp.Groups[2].Value));
AddDays(Int32.Parse(timestamp.Groups[3].Value));
AddHours(Int32.Parse(timestamp.Groups[4].Value));
AddMinutes(Int32.Parse(timestamp.Groups[5].Value));
AddSeconds(Int32.Parse(timestamp.Groups[6].Value));
if (!string.IsNullOrWhiteSpace(timestamp.Groups[7].Value))
{
AddMilliseconds(Int32.Parse(timestamp.Groups[7].Value));
}
if (!string.IsNullOrWhiteSpace(timestamp.Groups[8].Value))
{
utcOffset = Double.Parse(timestamp.Groups[8].Value, CultureInfo.InvariantCulture);
}
return true;
}
else
{
return false;
}
}
public string ToFormattedString()
{
string timezonePreSign = "Z";
if (utcOffset < 0)
{
timezonePreSign = "";
}
return string.Format("{0}-{1}-{2}T{3}:{4}:{5}.{6}{7}{8}", year, month, dayOfMonth, hours, minutes, seconds, miliseconds, timezonePreSign, utcOffset.ToString().Replace(',','.'));
}
public DateTime ToDateTime()
{
DateTimeKind dateTimeKind;
if(utcOffset == 0)
{
dateTimeKind = DateTimeKind.Utc;
}
else
{
dateTimeKind = DateTimeKind.Local;
}
return new DateTime(year, month, dayOfMonth, hours, minutes, seconds, miliseconds, dateTimeKind);
}
public override string ToString()
{
return this.ToFormattedString();
}
public void FromDateTime(DateTime timestamp)
{
TimeSpan utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(timestamp);
this.utcOffset = utcOffset.Hours + (utcOffset.Minutes / 100);
AddMilliseconds(timestamp.Millisecond);
AddSeconds(timestamp.Second);
AddMinutes(timestamp.Minute);
AddHours(timestamp.Hour);
AddDays(timestamp.Day);
AddMonths(timestamp.Month);
AddYears(timestamp.Year);
}
public void Add(TimeSpan timeSpan)
{
AddMilliseconds(timeSpan.Milliseconds);
AddSeconds(timeSpan.Seconds);
AddMinutes(timeSpan.Minutes);
AddHours(timeSpan.Hours);
AddDays(timeSpan.Days);
}
public void AddMilliseconds(int val)
{
if (val + miliseconds >= 1000)
{
AddSeconds( val / 1000);
miliseconds = (val % 1000);
}
else
{
miliseconds += val;
}
}
private void AddSeconds(int val)
{
if (seconds + val >= 60)
{
AddMinutes(val / 60);
seconds = (val % 60);
}
else
{
seconds += val;
}
}
private void AddMinutes(int val)
{
if (minutes + val >= 60)
{
AddMinutes(val / 60);
minutes = (val % 60);
}
else
{
minutes += val;
}
}
private void AddHours(int val)
{
if (hours + val >= 24)
{
AddDays (val / 24);
hours = (val % 24);
}
else
{
hours += val;
}
}
private void AddDays(int val)
{
short dayCount = GetDayMaxDaysOfMonth(month, year);
if (dayOfMonth + val > dayCount)
{
AddMonths(val / dayCount);
dayOfMonth = (val % dayCount);
}
else
{
dayOfMonth += val;
}
}
private void AddMonths(int val)
{
if (month + val > 12)
{
AddYears(val / 12);
month = (val % 12);
}
else
{
month += val;
}
}
private void AddYears(int val)
{
year += val;
}
public override bool Equals(object o)
{
if (o is SyslogTimestamp)
{
return DoMatch((SyslogTimestamp)o, this);
}
else
{
return false;
}
}
public static bool DoMatch(SyslogTimestamp a, SyslogTimestamp b)
{
bool doMatch = (a.year == b.Year)
&& (a.month == b.Month)
&& (a.dayOfMonth == b.DayOfMonth)
&& (a.hours == b.Hours)
&& (a.minutes == b.Minutes)
&& (a.seconds == b.Seconds)
&& (a.miliseconds == b.Miliseconds)
&& (a.utcOffset == b.UtcOffset);
return doMatch;
}
public static bool operator ==(SyslogTimestamp a, SyslogTimestamp b)
{
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
if (((object)a == null) || ((object)b == null))
{
return false;
}
return DoMatch(a, b);
}
public static bool operator !=(SyslogTimestamp a, SyslogTimestamp b)
{
return !(a == b);
}
public static bool operator <(SyslogTimestamp a, SyslogTimestamp b)
{
if (a.Year < b.Year) { return true; }
if (a.Year > b.Year) { return false; }
if (a.Month < b.Month) { return true; }
if (a.Month > b.Month) { return false; }
if (a.DayOfMonth < b.DayOfMonth) { return true; }
if (a.DayOfMonth > b.DayOfMonth) { return false; }
if ((a.Hours + a.UtcOffset) < (b.Hours + b.UtcOffset)) { return true; }
if ((a.Hours + a.UtcOffset) > (b.Hours + b.UtcOffset)) { return false; }
if (a.Minutes < b.Minutes) { return true; }
if (a.Minutes > b.Minutes) { return false; }
if (a.Seconds < b.Seconds) { return true; }
if (a.Seconds > b.Seconds) { return false; }
if (a.Miliseconds < b.Miliseconds) { return true; }
if (a.Miliseconds > b.Miliseconds) { return false; }
return false;
}
public static bool operator >(SyslogTimestamp a, SyslogTimestamp b)
{
if (a.Year > b.Year) { return true; }
if (a.Year < b.Year) { return false; }
if (a.Month > b.Month) { return true; }
if (a.Month < b.Month) { return false; }
if (a.DayOfMonth > b.DayOfMonth) { return true; }
if (a.DayOfMonth < b.DayOfMonth) { return false; }
if ((a.Hours + a.UtcOffset) > (b.Hours + b.UtcOffset)) { return true; }
if ((a.Hours + a.UtcOffset) < (b.Hours + b.UtcOffset)) { return false; }
if (a.Minutes > b.Minutes) { return true; }
if (a.Minutes < b.Minutes) { return false; }
if (a.Seconds > b.Seconds) { return true; }
if (a.Seconds < b.Seconds) { return false; }
if (a.Miliseconds > b.Miliseconds) { return true; }
if (a.Miliseconds < b.Miliseconds) { return false; }
return false;
}
public static bool operator >=(SyslogTimestamp a, SyslogTimestamp b)
{
return (a > b) || DoMatch(a, b);
}
public static bool operator <=(SyslogTimestamp a, SyslogTimestamp b)
{
return (a < b) || DoMatch(a, b);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}
Clean-up crew needed, grammar spill... - Nagy Vilmos
|
|
|
|
|
Your showing of the "fff" format characters prompted me to see if you can expand them out to six characters and use the TryParseExact overload that excepts an array of formats. It does. A little more playing around with the formats and it all becomes so simple after all.
This is real simple now especially after I noticed the other overload on TryParseExact that takes an array of formats to test.
string[] formats = { "yyyy-MM-dd\\THH:mm:ss\\Z",
"yyyy-MM-dd\\THH:mm:ss.f\\Z",
"yyyy-MM-dd\\THH:mm:ss.ff\\Z",
"yyyy-MM-dd\\THH:mm:ss.fff\\Z",
"yyyy-MM-dd\\THH:mm:ss.ffff\\Z",
"yyyy-MM-dd\\THH:mm:ss.fffff\\Z",
"yyyy-MM-dd\\THH:mm:ss.ffffff\\Z",
"yyyy-MM-dd\\THH:mm:sszzz",
"yyyy-MM-dd\\THH:mm:ss.fzzz",
"yyyy-MM-dd\\THH:mm:ss.ffzzz",
"yyyy-MM-dd\\THH:mm:ss.fffzzz",
"yyyy-MM-dd\\THH:mm:ss.ffffzzz",
"yyyy-MM-dd\\THH:mm:ss.fffffzzz",
"yyyy-MM-dd\\THH:mm:ss.ffffffzzz"
};
DateTime dt1 = default(DateTime);
bool res1 = System.DateTime.TryParseExact("1985-04-12T20:20:59.100000-00:15",
formats, System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AdjustToUniversal,
out dt1);
DateTime dt2 = default(DateTime);
bool res2 = System.DateTime.TryParseExact("1985-04-12T20:20:59.100001-00:15",
formats, System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AdjustToUniversal,
out dt2);
Console.WriteLine(dt1.Kind.ToString());
Console.WriteLine(dt1.ToString("u"));
Console.WriteLine((dt1 < dt2).ToString());
This code works, but has the drawback of loosing the original offsets as everything gets adjusted to UTC.
You can maintain the original offset date by using the DateTimeOffset [^]structure (this structure has all the functionality that I so foolishly recreated by custom parsing). Oh, well it was fun to see if I could do it.
DateTimeOffset dto1 = new DateTimeOffset();
bool res1b = System.DateTimeOffset.TryParseExact("1985-04-12T20:20:59.100000-00:15",
formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeLocal,
out dto1); Notice the change to AssumeLocal. The DateTime and Offset properties can then be used to recreate the original string.
|
|
|
|
|
I have a file in which each line has a fixed length 1600 char
but each line has its there are different columns
Line 1 will be like this
RA01XYZ--------------------------------------------------------------------201401231
RA is Record Type
01 is Version
XYZ------------------ is client name
201401231 is date
now 2 line
SR0123456789-------------------------011234567890-
SR is record type
0123456789------------------------- is some number
You see that each line will have its own set of defined columns and it cannot be fixed width
So my question is, is it possible/advisable to apply SSIS on this or create a simple win form application using REGEX to extract and process the data.
|
|
|
|
|
Regex? No, Substring(start, length).
Read a whole line, determine the "line type", and then get its data into appropriate objects which you then insert into the db.
|
|
|
|
|
Bernhard Hiller wrote: get its data into appropriate objects
Which he may do by using an appropriate regex, so not a really bad start.
Clean-up crew needed, grammar spill... - Nagy Vilmos
|
|
|
|
|
ok, but i want a view on processing this type of file using ssis??
is it doable and advisable
|
|
|
|
|
Hi my name is vishal.For past 10 days i have been going nuts over of how to create barcode in c# windows forms with sql server 2008 using StrokeScribe control of version 4.3.2. i have done some coding here with 5 group boxes with no success. i have four group boxes
1) group box-1-name:fmeStep1,text:Step 1,visible:true.
It has 8 labels,2 comboboxes,3 textboxes,3 datetimepickers.
2) group box-2-name:fmeBarCode,text:"",visible:true
It has i label,i textbox.
3) group box-3-name:fmeDEntry,text:Dialyzer Entry,visible:true.
It has 2 radio buttons
4) group box-4-name:fmeStep2,text:Step 3,visible=true.
It has i textbox named txtDID,visible=true,enabled=true.1 button,1 strokescribe control of version:4.3.2.,name:barCDialyzer.Given below is properties of barCDialyzer:
AccessibeRole: Default
AlowDrop: false
Alphabet: EAN13
AztecECL: 23
AztecMinLayer: 1
BitmapH: 1
BiwmapW: 115
CausesValidation: true
CheckDigit: 8
CodabarHasCheckDigit: false
Code11CheckDigits: 1
Code39HasCheckDigit: false
Code39Ratio: 2
CodePage: 3
CompactPDF417: false
ECI: 0
Enabled: true
GraphicsMode: Advanced
HBorderSize: 10
I2of5Ratio: 2
ISBN10: false
ITF14BearerBox: false
ITF14BearerWidth: 5
ProcessTilde: false
QrECL: L
QrMinVersion: 1
QuietZone2D: 1
SaCount: 0
SaID: 0
SaPos: 0
ShowText: true
TextJustify: true
TextOffset: 0
UTF8: false
VBorderPercent: 5
Visible: true.
5) group box-5-name:fmeStep3,text:Step 4,visible:true.
it has 1 combobox,2 buttons,2 picturebox.
1-picturebox:pictureBox1,enabled=true,visible=true. in which i have another strokescribe named:barCOrg an a label named lblPID. given below are it's properties:
AlowDrop: false
Alphabet: EAN13
AztecECL: 23
AztecMinLayer: 1
BitmapH: 1
BiwmapW: 115
CausesValidation: true
CheckDigit: 8
CodabarHasCheckDigit: false
Code11CheckDigits: 1
Code39HasCheckDigit: false
Code39Ratio: 2
CodePage: 3
CompactPDF417: false
ECI: 0
Enabled: true
GraphicsMode: Advanced
HBorderSize: 10
I2of5Ratio: 2
ISBN10: false
ITF14BearerBox: false
ITF14BearerWidth: 5
ProcessTilde: false
QrECL: L
QrMinVersion: 1
QuietZone2D: 1
SaCount: 0
SaID: 0
SaPos: 0
ShowText: true
TextJustify: true
TextOffset: 0
UTF8: false
VBorderPercent: 5
Visible: true.
2-picturebox:pictureBox2,enabled=true,visible=false.I have embedded this pictureBox2 on pictureBox1.Given below is code of my form named:Dialyzer in which i have 2 buttons..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using STROKESCRIBECLSLib;
using System.Data.SqlClient;
namespace DRRS_in_Csharp
{
public partial class Dialyzer : Form
{
Int32 dStepIndex;
long pUserID = 1;
SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Tuscan46;Integrated Security=true");
SqlCommand cmd;
SqlDataAdapter drp;
DataSet ds;
string str;
DataTable dt;
public Dialyzer()
{
InitializeComponent();
SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Tuscan46;Integrated Security=true");
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
string SqlDataPull=("Select p.patient_id as patient_id,n.patient_first_name as patient_fname,n.patient_last_name as patient_lname from PATIENT_NAME6 n,PATIENT_ID6 p where n.patient_id=p.patient_id");
SqlCommand cmd=new SqlCommand(SqlDataPull);
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
SqlDataPull=dr[0].ToString()+dr[1].ToString()+dr[2].ToString();
cboPatientID.Items.Add(SqlDataPull);
}
dr.Close();
string SqlDataPull1=("Select ManufacturerName from EQUIPMENTDATA");
cmd=new SqlCommand(SqlDataPull1);
cmd.Connection=conn;
cmd.CommandType=CommandType.Text;
dr=cmd.ExecuteReader();
while(dr.Read())
{
SqlDataPull1 = dr[0].ToString();
cboManufacturer.Items.Add(SqlDataPull1);
}
}
private void cboequipment_Type_Click(object sender,EventArgs e)
{
if(cboManufacturer.SelectedIndex==-1)
{
return;
}
SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Tuscan46;Integrated Security=true");
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
DataTable dt=new DataTable();
cmd=new SqlCommand("Select * from EQUIPMENTDATA where ManufacturerName='"+cboManufacturer.Text+"' and volume='"+cboequipmentType.Text+"'",conn);
}
private void cboManufacturer_Click(object sender,EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Tuscan46;Integrated Security=true");
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
DataTable dt = new DataTable();
dt.Clear();
SqlDataAdapter adp = new SqlDataAdapter();
cmd=new SqlCommand("Select volume from EQUIPMENTDATA where ManufacturerName='" + cboManufacturer.Text + "'",conn);
adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
}
private void cboPatientID_Click(object sender,EventArgs e)
{
if(cboPatientID.SelectedIndex!=-1)
{
btnSearch.Enabled=true;
button3.Enabled=true;
SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Tuscan46;Integrated Security=true");
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd=new SqlCommand("Select * from PATIENT_NAME where patient_id="+cboPatientID.GetItemText(cboPatientID.SelectedIndex)+"'",conn);
if(txtDID.Text.Length>5)
{
txtDID.Text=txtDID.Text.Substring(0,5);
}
DataTable dt=new DataTable();
if(dt.Rows.Count==-1)
{
if((cmd.Parameters.AddWithValue("@virology",SqlDbType.Int).Value.GetHashCode()==0))
{
txtDID.Text=txtDID.Text+1;
}
else
{
txtDID.Text=txtDID.Text+0;
}
}
else
{
txtDID.Text=txtDID.Text+0;
}
lblPID.Text=cboPatientID.Text.Substring(cboPatientID.Text.IndexOf(cboPatientID.Text,1));
barCDialyzer.Alphabet=STROKESCRIBELib.enumAlphabet.AZTEC;
barCDialyzer.CtlText=txtDID.Text+(char)9;
barCOrg.Alphabet=STROKESCRIBELib.enumAlphabet.AZTEC;
barCOrg.CtlText=txtDID.Text+(char)9;
int rc=0;
rc =barCOrg.SavePicture("D:\\Workarea\vishal\vishal c#\\DRRS in Csharp\\DRRS in Csharp\bar1.bmp", STROKESCRIBELib.enumFormats.BMP,barCOrg.BitmapW,barCOrg.BitmapH);
if(rc>0)
{
MessageBox.Show(barCOrg.ErrorDescription);
}
else
{
btnSearch.Enabled=false;
button3.Enabled=false;
}
}
}
private void barCDialyzer_Enter(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if(txtDID.Tag.ToString()=="0")
{
btnNext.Enabled=true;
button1.Enabled=false;
txtDID.Enabled=false;
barCDialyzer.Alphabet=STROKESCRIBELib.enumAlphabet.AZTEC;
barCDialyzer.CtlText=txtDID.Text+(char)9;
barCOrg.Alphabet=STROKESCRIBELib.enumAlphabet.AZTEC;
barCOrg.CtlText=txtDID.Text+(char)9;
int rc = 0;
rc = barCOrg.SavePicture("D:\\Workarea\vishal\vishal c#\\DRRS in Csharp\\DRRS in Csharp\bar1.bmp", STROKESCRIBELib.enumFormats.BMP, barCOrg.BitmapW, barCOrg.BitmapH);
if (rc > 0)
{
MessageBox.Show(barCOrg.ErrorDescription);
}
}
}
private void btnNext_Click(object sender, EventArgs e)
{
if (fmeDEntry.Visible == true)
{
fmeDEntry.Visible = false;
}
if (optDEntry1.Checked == false)
{
fmeBarCode.Visible = false;
fmeStep1.Visible = true;
}
{
if (dStepIndex == 0)
{
string dFieldName = "";
Boolean vEmptyB = false;
if (cboManufacturer.SelectedIndex == -1)
{
vEmptyB = true;
dFieldName = "Please select a manufacturer";
}
else if (cboequipmentType.SelectedIndex == -1)
{
vEmptyB = true;
dFieldName = "Please select size of dialyzer";
}
else if (txtMFRRefNo.Text.ToString().Trim() == "")
{
vEmptyB = true;
dFieldName = "Please enter equipment reference number";
}
else if (txtMFRLotNo.Text.ToString().Trim() == "")
{
vEmptyB = true;
dFieldName = "Please enter equipment lot number";
}
else if (txtPVol.Text.ToString().Trim() == "")
{
vEmptyB = true;
dFieldName = "Please enter packed_volume of equipment";
}
if (vEmptyB == true)
{
MessageBox.Show(dFieldName + "should not be empty");
return;
}
SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Tuscan46;Integrated Security=true");
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
string dDID = "";
cmd = new SqlCommand("select max(agn) from DIALYSER", conn);
cmd = new SqlCommand("Insert into DIALYSER(agn)" + "Values(@agn)", conn);
DataTable dt = new DataTable();
if (dt.Rows.Count != -1)
{
if (cmd.Parameters.AddWithValue("@agn", SqlDbType.Int).Value is DBNull)
{
dDID = "1";
}
else
{
dDID = cmd.Parameters.AddWithValue("@agn", SqlDbType.Int).Value.ToString() + 1;
txtDID.Text = txtDID.Text.Replace(dDID.PadLeft(5), dDID.Length.ToString()) + dDID;
}
}
else
{
txtDID.Text = txtDID.Text.Replace(dDID.PadLeft(5), dDID.Length.ToString()) + dDID;
}
}
fmeStep1.Visible = false;
fmeStep2.Visible = true;
fmeStep3.Visible = false;
btnNext.Enabled = false;
button1.Enabled = false;
txtDID.Focus();
}
}
private void fmeStep3_Enter(object sender, EventArgs e)
{
}
private void btnSearch_Click(object sender, EventArgs e)
{
string dPatientID;
dPatientID=cboPatientID.GetItemText(cboPatientID.SelectedIndex);
Patient p=new Patient();
p.loadPatient(dPatientID);
}
private void button3_Click(object sender, EventArgs e)
{
string dFieldName = "";
Boolean vEmptyB=false;
if(cboManufacturer.SelectedIndex==-1)
{
vEmptyB = true;
dFieldName = "Please select a manufacturer";
}
else if(cboequipmentType.SelectedIndex==-1)
{
vEmptyB = true;
dFieldName = "Please select size of equipment";
}
else if(txtMFRRefNo.Text.ToString().Trim()=="")
{
vEmptyB = true;
dFieldName = "Equipment reference number should not be empty";
}
else if(txtMFRLotNo.Text.ToString().Trim()=="")
{
vEmptyB = true;
dFieldName = "Equipment lot number should not be empty";
}
else if(txtPVol.Text.ToString().Trim()=="")
{
vEmptyB = true;
dFieldName = "Packed volume of the equipment should not be empty";
}
else if(cboPatientID.SelectedIndex==-1)
{
vEmptyB = true;
dFieldName = "Please select a patient";
}
if (vEmptyB==true)
{
MessageBox.Show(dFieldName+"should not be empty");
return;
}
SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Tuscan46;Integrated Security=true");
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd=new SqlCommand("Insert into DIALYSER(dialyserID,manufacturer,mfr_ref_number,mfr_lot_number,mfr_date,exp_date,start_date,packed_volume,dialyzer_size,patient_id,row_upd_date,user_id)"+"Values(@dialyserID,@manufacturer,@mfr_ref_number,@mfr_lot_number,@mfr_date,@exp_date,@start_date,@packed_volume,@dialyzer_size,@patient_id,GetDate(),@user_id)",conn);
cmd.Parameters.AddWithValue("@dialyserID",txtDID.Text);
cmd.Parameters.AddWithValue("@manufacturer",cboManufacturer.SelectedIndex);
cmd.Parameters.AddWithValue("@mfr_ref_number",txtMFRRefNo.Text);
cmd.Parameters.AddWithValue("@mfr_lot_number",txtMFRLotNo.Text);
cmd.Parameters.AddWithValue("@mfr_date",dtMFRDate.Value);
cmd.Parameters.AddWithValue("@exp_date",dtMFRexpDate.Value);
cmd.Parameters.AddWithValue("@start_date",dtMFRstartDate.Value);
cmd.Parameters.AddWithValue("@packed_volume",txtPVol.Text);
cmd.Parameters.AddWithValue("@dialyzer_size",cboequipmentType.SelectedIndex);
cmd.Parameters.AddWithValue("@patient_id",cboPatientID.GetItemText(cboPatientID.SelectedIndex));
cmd.Parameters.AddWithValue("@user_id",pUserID);
cmd.ExecuteNonQuery();
((MDIParent5)this.MdiParent).updateUserActivities(pUserID, 4,txtDID.Text + "Dialyzer detail was successfully assigned to patient="+cboPatientID.SelectedIndex+"");
conn.Close();
this.Close();
}
private void GetData(string ID)
{
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Tuscan46;Integrated Security=true");
conn.Open();
SqlCommand cmd = new SqlCommand("Select * from EQUIPMENTDATA where ManufacturerName='" + cboManufacturer.Text + "' and volume='" + cboequipmentType.Text + "' and packed_volume='" + txtPVol.Text + "'", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
cboequipmentType.Text = dt.Rows[3]["volume"].ToString();
txtPVol.Text = dt.Rows[5]["packed_volume"].ToString();
}
conn.Close();
}
private void Dialyzer_Load(object sender, EventArgs e)
{
dtMFRDate.MinDate = dtMFRDate.Value;
dStepIndex=0;
fmeStep1.Visible=true;
fmeStep2.Visible=false;
fmeStep3.Visible=false;
}
private void txtDID_LostFocus(object sender, EventArgs e)
{
if (txtDID.Text.ToString().Trim() == "")
{
MessageBox.Show("Please enter Dialyzer ID to create", "DRRS", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtDID.Focus();
}
else
{
checkDialyzerID();
}
}
private void checkDialyzerID()
{
SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Tuscan46;Integrated Security=true");
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
DataTable dt = new DataTable();
cmd=new SqlCommand("Select * from DIALYSER where dialyserID="+txtDID.Text+"",conn);
if (dt.Rows.Count != -1)
{
MessageBox.Show("The DialyzerID already exists.Please try with another", "DRRS", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtDID.Text = "";
txtDID.Focus();
txtDID.Tag = 1;
}
else
{
txtDID.Tag = 0;
button1.Enabled = true;
button1.Focus();
}
conn.Close();
}
private void dtMFRDate_ValueChanged(object sender, EventArgs e)
{
dtMFRstartDate.MinDate = Convert.ToDateTime("21/10/2013");
}
private void txtPVol_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar))
{
e.Handled = true;
}
}
private void cboManufacturer_SelectedIndexChanged(object sender, EventArgs e)
{
GetData(cboManufacturer.SelectedItem.ToString());
}
private void cboequipmentType_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Tuscan46;Integrated Security=true");
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
str = "Select distinct(volume) from EQUIPMENTDATA where Manufacturername='" + cboManufacturer.Text + "'";
cmd = new SqlCommand(str, conn);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
txtPVol.Text = reader["packed_volume"].ToString();
}
conn.Close();
reader.Close();
}
private void button5_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Now here is the problem i am facing upon testing though entries process goes correctly till group box name:fmeStep1 afterwards i am not able get even controls of group box named:fmeStep2 and i dont know why? I want to see controls in fmeStep2 since in textbox named txtDID it shows me ID of Dialyzer that i am going to create and then in group box named:fmeStep3 i get to search for patient that i have to assign ID of Dialyzer to patient. I have tried fixing this problem many times but with no success. i am supposed to use StrokeScribe of version 4.3.2 only since it's my Boss orders and that i have to create barcode of type ean-13 in c# windows forms using StrokeScribe control with sql server 2008. Can anyone help me please where have i gone wrong in the coding. Can anyone guide me please. i was referred by Microsoft Developer Network community to ask my doubts regarding creation of barcode of type ean-13 in c# windows forms with sql server 2008. Can anyone help me please.?Any help or guidance would be greatly appreciated.
|
|
|
|
|