|
The first thing would be to split the sting into date and time components. From there replace the delimiter characters with appropriate separators for the part, / or - for date and : for time. Of course where there is no delimiter you'll have to resort to substring parsing or regex replacement. You'll have teh problem though of trying to determine what format the date is in, mm/dd/yyyy, dd/mm/yyyy, yyyy/mm/dd or any combination. The way to control this is specify the format to use and reject if not in that format.
Once you have the date and time parts, use DateTime.TryParse()
string date = "04/15/2010";
string time = "13:54:32";
DateTime dt = new DateTime();
if(DateTime.TryParse(date + " " + time, out dt))
{
}
I know the language. I've read a book. - _Madmatt
|
|
|
|
|
Hi guys thank you for the reply:
The problem I have is not with putting my string into the DateTime.
I need to pinpoint each character in my original string, to match my Format string.
To extract that values with in the original string. that represents its character in my format string.
eg:
String 1= "#2011-04-30 15:23:22"
String 2= "_yyyy-MM-dd HH:mm:ss"
so that yyyy = 2010, and MM=04 etc.
Then I need to use that values and build my string to put into the DateTime.
But both these 2 strings can be in any order, so if that happens, I can change my format string (String2)
to match that format in String1 and still get the value that correspond to the value I need from String 1.
Hope this clears it up a bit.
Thanks so much for the help up to date.
|
|
|
|
|
As Luc has shown you should be able to parse the strings and use it in DateTime.TryParse
DateTime dt;
DateTime.TryParseExact(string1, string2, null, DateTimeStyles.None, out dt);
I know the language. I've read a book. - _Madmatt
|
|
|
|
|
I'm afraid I changed my mind about my approach, see my other reply to you.
|
|
|
|
|
Is it possible to replace every non - numerical character in the string to 1 special character you use for delimeting? then TryParse the string with that format to a date.
V.
|
|
|
|
|
yes, that seems the best so far; provided:
- you choose a special character other than ':' and '/'
- you don't need AM/PM nor month names
public override void Test(int arg) {
test("2010.04.30.13.45.33", "yyyy.MM.dd.HH.mm.ss");
test("2010.04.30.13.4.3", "yyyy.MM.dd.HH.m.s");
test("2010.4.2.3.4.3", "yyyy.M.d.H.m.s");
}
private void test(string data, string format) {
DateTime dt;
bool OK=DateTime.TryParseExact(data, format, null, DateTimeStyles.None, out dt);
log("data="+data.PadRight(20)+"format="+format.PadRight(20)+" OK="+OK+" dt="+dt.ToString());
}
yields
data=2010.04.30.13.45.33 format=yyyy.MM.dd.HH.mm.ss OK=True dt=30-Apr-2010 13:45:33
data=2010.04.30.13.4.3 format=yyyy.MM.dd.HH.m.s OK=True dt=30-Apr-2010 13:04:03
data=2010.4.2.3.4.3 format=yyyy.M.d.H.m.s OK=True dt=02-Apr-2010 3:04:03
|
|
|
|
|
Basically what I was saying "replace the delimiter characters with appropriate separators for the part". I just didn't understand the need to support multiple formats.
I know the language. I've read a book. - _Madmatt
|
|
|
|
|
I would just use a Regular Expression Replace to standardize the string:
outdate = System.Text.RegularExpressions.Regex.Replace
(
indate
,
@"(?ix)(?:(?:DH\#(?'Year'\d\d\d\d)-(?'Month'\d\d)-(?'Day'\d\d)-(?'Hour'\d\d):(?'Minute'\d\d):(?'Second'\d\d))|
(?:\#(?'Month'\d\d)\#(?'Year'\d\d\d\d)\#(?'Day'\d\d)\#(?'Hour'\d\d)\#(?'Minute'\d\d)\#(?'Second'\d\d)\#)|
(?:DT(?'Day'\d\d)(?'Month'\d\d)(?'Year'\d\d\d\d)-(?'Hour'\d\d)(?'Minute'\d\d)(?'Second'\d\d)))"
,
@"${Year}-${Month}-${Day}-${Hour}:${Minute}:${Second}"
) ;
and only use one parse format.
|
|
|
|
|
Please can any one tell me how i can get which gridviewcell(gridview asp.net) is clicked.
please send me complete code.
Thanks in advance
jitendra sandu
|
|
|
|
|
See here[^] for complete details. You will have to write the code for yourself.
It's time for a new signature.
|
|
|
|
|
Hi Folks,
I currently have an issue where I'm trying to write some code to allow me to return an object from a web service. When this object is based on a Struct, all's good. However, when I replace the Struct with a [Serializable]Class, compile, and run the service, on invoking the method which is to return the class object, I receive the below error:
======================================================================================================
Server Error in '/' Application.
--------------------------------------------------------------------------------
This type of page is not served.
Description: The type of page you have requested is not served because it has been explicitly forbidden. The extension '.asp' may be incorrect. Please review the URL below and make sure that it is spelled correctly.
Requested URL: /default.asp
======================================================================================================
The reason I'd like to move from using a Struct to a Class is this would allow me to take advantage of interfaces and generics, to move the code which currently populates the Struct's properties from a DbDataReader's values into a delegate function, which can take a reader and a list of each field's type, and convert each record to an instance of the Struct.
Thanks in advance.
JB
|
|
|
|
|
|
The type of object has nothing to do with your problem. Basically, you have something trying to serve up default.asp and this extension has not been allowed by your web server. I suspect that you should actually have default.aspx in there.
"WPF has many lovers. It's a veritable porn star!" - Josh Smith As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.
My blog | My articles | MoXAML PowerToys | Onyx
|
|
|
|
|
Hi guys,
does anyone know where i can get a list of mssql error codes. i need to enumerate the errors and treat anyone specifically. For ex: if it generates a unique key violation or foreign key violation, i could work on that.
Thanx.
He who goes for revenge must first dig two graves.
|
|
|
|
|
|
I've had to do that, but I handle only the ones I've actually encountered, not all of them.
My DatabaseAccessor[^] article contains my SqlServerErrorInfo.cs and DatabaseException.cs files which may be of use to you.
|
|
|
|
|
Hi Experts,
I am having a datatable object which is getting populated dynamically. My requirement is that i need to check whether the datatable contains any column with the name of "recordid". I have achieved this by doing the following
m_dataTable.Columns.Contains("recordid")
But my problem is that the column names might not come as "recordid" but might contain special characters. So my column name might be any of (but not restricted to) the following
1. Record Id
2. RECORD ID
3. Record_Id
4. Record-Id
I have a solution of passing each string to a method which is posted on this link but this approach will hamper performance.
Can anyone please help?
Thanks in advance!
Regards,
Samar
|
|
|
|
|
i think you should filter it, i mean when you will filter it you should look for your special character if you find it then replace it with space or null.
Ex:
recored_id => recordid
EASY COME EASY GO
|
|
|
|
|
Yes that is a solution i have but i think this is hit performance. Also maintanence wise also it will be a overhead.
Regards,
Samar
|
|
|
|
|
|
Hi Jinal i have this solution with me but this is implemented on 1 string and not on a collection right? For the above to work I would need to loop through the collection and then check. I need something which can be applied directly on the collection without looping.
Regards,
Samar
|
|
|
|
|
Sorry dear.
For collection you have to use looping.
Jinal Desai - LIVE
|
|
|
|
|
As Jinal suggest, use a regular expression.
But I would use a regex to match the whole string you want:
Regex regex = new Regex("(Record.ID)|(RecordID)",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
string result = regex.Replace(InputText,""); This would remove any text containing "record" followed by "id" or any character then "id" in any combination of upper or lower case.
You should never use standby on an elephant. It always crashes when you lift the ears. - Mark Wallace
C/C++ (I dont see a huge difference between them, and the 'benefits' of C++ are questionable, who needs inheritance when you have copy and paste) - fat_boy
|
|
|
|
|
I'm getting a "Cross-thread operation not valid" error when I call Refresh() on a custom .NET Marquee control. This control used to be working in prior .NET projects and I'm trying to get it going again, eventually with hopes of posting as an article. It was really a great Marquee control in that it could display both text and graphics and could run in any direction, etc. I've included the full source to the control and to the demo form I'm trying to test it with. To help resolve the problem and for anyone else that might benefit from the control. I just can't figure out why I'm calling the
controls.Refresh() method from a cross thread. If anyone can shed some light on this, it would be greatly appreciated.
Aaron
Here's the code for the marquee control:
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Text;
using System.Drawing.Design;
using System.Timers;
namespace RADMarquee
{
[DefaultProperty("DrawingMode"),
DefaultEvent("DrawingModeChanged")]
public class Marquee : System.Windows.Forms.UserControl
{
#region Privat Members
Graphics _gfx;
int x, y; // coords of top left corner of graphic
float StringWidth = 0;
float StringHeight = 0;
int BoxPaddingTop = 2;
bool bNewBrush = true;
SolidBrush BrushBG;
SolidBrush BrushBG2;
SolidBrush BrushFG;
System.Timers.Timer _tmrMain;
bool bNewText = true;
public enum Direction
{
Up, Down, Right, Left
};
public enum TextRefreshTiming
{
Async, TextOffScreen
};
const string _sMessageDelimiter = "!^#-=_";
const string sBR = "\r\n";
float StringPadding = 2;
#endregion
#region Properties
TextRefreshTiming _refreshTiming = TextRefreshTiming.Async;
[Browsable(true),
ReadOnly(false),
Category("Marquee"),
Description("Not currently working. Async: Display new Text
right after Text is changed. "
+ "TextOffScreen: Wait until the Text scrolls off the screen
before restart.")]
public TextRefreshTiming TextRefreshTimimg
{
get{ return _refreshTiming; }
set
{
_refreshTiming = (TextRefreshTiming)value;
}
}
// Direction
Direction _direction = Direction.Left;
[Browsable(true),
Category("Marquee"),
Description("Marquee Scrolling Direction"),
ReadOnly(false)]
public Direction ScrollingDirection
{
get { return _direction; }
set
{
_direction = value;
}
}
// Refresh Rate
int iRefreshRate = 100;
[Browsable(true),
ReadOnly(false),
Category("Marquee"),
DefaultValue(typeof(int), "100"),
Description("How long to wait before redrawing the Marquee in
milliseconds (set this to a large value to improve perormance)")]
public int RefreshRate
{
get { return iRefreshRate; }
set
{
iRefreshRate = value;
}
}
// Speed
int iSpeed = 8;
[Browsable(true),
ReadOnly(false),
DefaultValue(typeof(int), "8"),
Category("Marquee"),
Description("How far to advance the Marquee during each
refresh")]
public int Speed
{
get { return iSpeed; }
set
{
iSpeed = value;
}
}
public int PauseCycles = 5;
// RegionColor
private Color _bgColor = Color.Black;
[Browsable(true),
ReadOnly(false),
DefaultValue(typeof(Color), "Color.Black"),
Category("Marquee"),
Description("Background Color of Marquee")]
public Color RegionColor
{
get { return _bgColor; }
set
{
_bgColor = value;
bNewBrush = true;
}
}
// BG2Color
private Color _bg2Color = Color.Black;
[Browsable(true),
ReadOnly(false),
DefaultValue(typeof(Color), "Color.Black"),
Category("Marquee"),
Description("Background Color of Marquee")]
public Color BGColor
{
get { return _bg2Color; }
set
{
_bg2Color = value;
bNewBrush = true;
}
}
// ForeColor
Color _foreColor = Color.Red;
[Browsable(true),
ReadOnly(false),
Category("Marquee"),
Description("Marquee Text Color"),
DefaultValue(typeof(Color), "Color.Red")]
public override Color ForeColor
{
get { return _foreColor; }
set
{
_foreColor = value;
bNewBrush = true;
}
}
// Font
private Font _font;
[Browsable(true),
ReadOnly(false),
Category("Marquee"),
Description("Marquee Font Properties ")]
public new Font Font
{
get { return _font; }
set
{
_font = value;
bNewText = true;
}
}
// DisplayText
StringBuilder _sbDisplayCurrent;
[Browsable(true),
Category("Marquee"),
Description("Marquee Display Text"),
ReadOnly(false)]
public string DisplayText
{
get
{
if(!Object.Equals(_sbDisplayCurrent, null))
{
return _sbDisplayCurrent.ToString();
}
else
{
return "";
}
}
set
{
if(Object.Equals(_sbDisplayCurrent, null)) // null
_sbDisplayCurrent
{
_sbDisplayCurrent = new StringBuilder(value);
}
LoadStringCollection(value);
// refresh String on next cycle
if(/*this.TextRefreshTimimg == TextRefreshTiming.Async &&
*/value != "")
{
bNewText = true;
StartDraw(0);
}
}
}
private void LoadStringCollection(string sVal)
{
_sbDisplayCurrent.Remove(0, _sbDisplayCurrent.Length);
_sbDisplayCurrent.Append(sVal);
}
// Enabled
bool bEnabled = true;
[Browsable(true),
ReadOnly(false),
DefaultValue(typeof(bool),"True"),
Category("Marquee"),
Description("Turn the Marquee off or on. Can be used to stop
scrolling")]
public new bool Enabled
{
get { return bEnabled; }
set
{
bEnabled = value;
}
}
#endregion
#region Events
// TextOffScreen
[Browsable(true),
ReadOnly(false),
Category("Marquee"),
Description("Event to raise when text has cleared visible area,
occurs just before TextEnd")]
public event EventHandler TextOffScreen;
// TextEnd
[Browsable(true),
ReadOnly(false),
Category("Marquee"),
Description("Event to raise when Marquee text has cycled once
and is about to start over, occurs just afterTextOffScreen")]
public event EventHandler TextEnd;
private System.ComponentModel.Container components = null;
#endregion
#region Constructor
public Marquee()
{
// this call is required by the Windows.Forms Form Designer.
_sbDisplayCurrent = new StringBuilder();
InitializeComponent();
this.Size = new Size(400,200);
this.Text = "Marquee";
SetStyle(ControlStyles.UserPaint, true); // enable dbl
bufferg
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.DoubleBuffer, true);
Init();
_tmrMain = new System.Timers.Timer();
_tmrMain.Elapsed += new
ElapsedEventHandler(this.DoDrawEvent);
_tmrMain.Interval = this.RefreshRate;
_tmrMain.Start();
}
#endregion
public void Quit()
{
this.Dispose();
}
public void Stop()
{
}
public void Init()
{
if (Object.Equals(_font, null))
_font = new Font("Arial", 14, FontStyle.Bold);
SetDefaults();
}
public void SetDefaults()
{
this.ForeColor = Color.Red;
this.BGColor = Color.Black;
this.RegionColor = Color.Black;
}
public void LoadBrushes()
{
bool bTmp = bEnabled; // save enabled state
bEnabled = false; // disable
// load colors
BrushBG = new SolidBrush(RegionColor);
BrushBG2 = new SolidBrush(BGColor);
BrushFG = new SolidBrush(ForeColor);
bEnabled = bTmp; //EnabledState.Disabled;
bNewBrush = false;
DrawBackground();
}
protected override void OnPaint(PaintEventArgs e)
{
_gfx = e.Graphics;
if(bNewBrush)
LoadBrushes();
if(bNewText)
BuildStringGraphic(e.Graphics);
_gfx.FillRectangle(BrushBG, 0, 0, Width, Height);
// add support here for using a different brush to draw the
strings/portions of the string
_gfx.DrawString(_sbDisplayCurrent.ToString(), _font, BrushFG,
x, y);
}
protected override void OnPaintBackground(PaintEventArgs
pevent)
{
// don't allow the background to paint
}
protected void BuildStringGraphic(Graphics g)
{
// examine the string for settings mark up
// <setting[\s\w\d\"]+/>
// message characters: [\w\s\d\.\"!-\+=&\*\(\)\$%@]+
// <setting bgcolor="" color="" font="" />
//ParseMessages(); // look for settings and apply here
if (Object.Equals(_sbDisplayCurrent, null) ||
Object.Equals(_font, null) || _sbDisplayCurrent.ToString() == "")
return;
StringFormat sfTrue =
(StringFormat)StringFormat.GenericTypographic.Clone();
sfTrue.Alignment = StringAlignment.Near;
sfTrue.LineAlignment = StringAlignment.Near;
SizeF dims = g.MeasureString(_sbDisplayCurrent.ToString(),
_font);
StringWidth = dims.Width;
StringHeight = dims.Height;
// set initial coords by direction
if(_direction == Direction.Right)
{
x = -(int)(StringPadding + StringWidth); // start at left
y = (int)((Height - StringHeight)/ 2 ) + BoxPaddingTop;
}
else if(_direction == Direction.Left)
{
x = (Width + (int)(StringPadding + StringWidth));
y = (int)((Height - StringHeight) / 2 ) + BoxPaddingTop;
}
else if(_direction == Direction.Up)
{
x = (int)StringPadding;
y = (int)(Height / 2);
}
else if(_direction == Direction.Down)
{
x = (int)StringPadding;
y = (int)-(Height / 2);
}
bNewText = false;
}
protected void DrawBackground()
{
Rectangle _rec = new Rectangle(0, BoxPaddingTop, Width,
Height - BoxPaddingTop * 2);
_gfx.FillRectangle(BrushBG2, _rec); // fill the second
background
}
public void DoDrawEvent(object sender, ElapsedEventArgs e)
{
DoDrawingCycle();
}
public void StartDraw(int iPauseCycles)
{
PauseCycles = iPauseCycles;
// don't do anything if this control is disabled
if(bEnabled == false || DisplayText == "")
return;
DoDrawingCycle();
}
protected void DoDrawingCycle()
{
if(_direction == Direction.Right)
{
this.MoveRight();
}
else if(_direction == Direction.Left)
{
this.MoveLeft();
}
else if(_direction == Direction.Down)
{
this.MoveDown();
}
else if(_direction == Direction.Up)
{
this.MoveUp();
}
}
public void MoveLeft()
{
int i = 0;
bool bTextCleared = false;
if( x < -(StringPadding + StringWidth) ) // restart from
right
{
x = Width + (int)StringPadding;
i = 0;
bTextCleared = false;
OnTextEnd(null);
}
else if (x < -(StringWidth) && !bTextCleared)
{
bTextCleared = true;
OnTextClear(null);
}
if(i < PauseCycles)
++i;
else
x = x - Speed;
// folling call is generating this error:
// Cross-thread operation not valid: Control 'mq' accessed
from a thread other than the thread it was created on.
Refresh();
}
public void MoveRight()
{
int i = 0;
bool bTextCleared = false;
if( x > (Width) ) // restart from left
{
x = -Width;
i = 0;
bTextCleared = false;
OnTextEnd(null);
}
else if (x == Width && !bTextCleared)
{
bTextCleared = true;
OnTextClear(null);
}
if(i < PauseCycles)
++i;
else
x = x + Speed;
Refresh();
}
public void MoveUp()
{
int i = 0;
bool bTextCleared = false;
if( y < -(StringPadding + StringHeight + Height) )
{
y = Height + (int)StringPadding;
x = 0;
i = 0;
bTextCleared = false;
OnTextEnd(null);
}
else if (y == -StringHeight && !bTextCleared)
{
bTextCleared = true;
OnTextClear(null);
}
if(i < PauseCycles)
++i;
else
y = y - Speed;
Refresh();
}
public void MoveDown()
{
int i = 0;
bool bTextCleared = false;
if( y > (Height + StringPadding) ) // restart from left
{
x = 0;
y = 0 - (int)StringHeight ;
i = 0;
bTextCleared = false;
OnTextEnd(null);
}
else if (y == Height && !bTextCleared)
{
bTextCleared = true;
OnTextClear(null); // no EventArgs
}
if(i < PauseCycles)
++i;
else
y = y + Speed;
Refresh();
}
#region Event Handling
// invoke delegates when the Marquee text has cleared the
display area
protected virtual void OnTextClear(MarqueeEventArgs e)
{
if (TextOffScreen != null && DisplayText != "")
{
// invokes the delegates.
TextOffScreen(this, e);
}
}
// invoke delegates when the marquee text has reached the
absolute end of its cycle
protected virtual void OnTextEnd(MarqueeEventArgs e)
{
if (TextEnd != null && DisplayText != "")
{
TextEnd(this, e);
}
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
private void Marquee_Resize(object sender, System.EventArgs e)
{
this.Invalidate();
}
#endregion
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new
System.Resources.ResourceManager(typeof(Marquee));
//
// Marquee
//
this.BackColor = System.Drawing.Color.WhiteSmoke;
this.BackgroundImage = ((System.Drawing.Image)
(resources.GetObject("$this.BackgroundImage")));
this.Name = "Marquee";
this.Resize += new System.EventHandler(this.Marquee_Resize);
}
#endregion
}
public class MarqueeEventArgs : EventArgs
{
int iFlags = 0;
public MarqueeEventArgs()
{
}
}
}
Here's the code for the demo form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace RadMarqueeDemo
{
public partial class Form1 : Form
{
private RADMarquee.Marquee mq;
private void MyInitializeComponent()
{
mq = new RADMarquee.Marquee();
this.mq.ForeColor = System.Drawing.Color.Red;
this.mq.BGColor = Color.Black;
this.mq.Location = new System.Drawing.Point(10, 10);
this.mq.Name = "mq";
this.mq.ScrollingDirection =
RADMarquee.Marquee.Direction.Left;
this.mq.Size = new System.Drawing.Size(300, 50);
mq.RefreshRate = 70;
this.mq.Speed = 7;
this.mq.TabIndex = 0;
this.Controls.Add(this.mq);
mq.Enabled = true;
mq.DisplayText = "Hello World!";
}
public Form1()
{
MyInitializeComponent();
InitializeComponent();
}
private void Form1_Load_1(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
this.mq.Enabled = true;
}
}
}
|
|
|
|
|
|