|
Note that the generic method resolved the first problem I was having, which is that it was returning DBNull in situations for non-nullable types. I understand that the DB field is returned as an object and I understand that the object returned is not going to be implicitly converted to the C# types.
What I can't understand is the syntax I need to use in the generic method. I suspect it's the <t> part because that's where I'm getting "Unable to cast type Object to type long" exceptions
public T DBToType<T> ( T value )
{
if ( !Convert.IsDBNull ( value ) )
{
return ( T ) Convert.ChangeType ( value , typeof ( T ) );
}
else
{
return default ( T );
}
}
|
|
|
|
|
I'm working on a WPF app that accesses its data from a DAL class hitting SQL on a server. Pretty standard.
I want to make the calls to the DAL async. So I have:
public async Task<CompanyEntity> GetCompany(int id)
{
using (var db = new JayhawkDB())
{
CompanyEntity results = null;
try
{
var query = from x in db.Companies
where x.Id == id
select x;
var record = query.FirstOrDefault<Company>();
results = new CompanyEntity
{
Id = record.Id,
CreatedById = record.CreatedById,
CreatedDT = record.CreatedDt,
DeletedById = record.DeletedById.GetValueOrDefault(),
DeletedDT = record.DeletedDt.GetValueOrDefault(),
CompanyName = record.CompanyName,
Abbreviation = record.Abbreviation,
Notes = record.Notes
};
}
catch (Exception e)
{
throw;
}
return results;
}
}
I get a warning under the method name that says "The method lack await operators and will run synchronously..."
That message is correct. The really isn't anything here to await on. Therefore this will be a blocking call.
I want the ViewModel to call through the BL an into the DAL and have the VM await the call so the UI doesn't get blocked.
What the right way to do this?
Thanks
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
You only need the async modifier if you've got an await in the method. All this method needs to do is return a Task or some kind, which your method isn't doing. A dirty conversion of your code to returning a Task would be:
public Task<CompanyEntity> GetCompany(int id)
{
return Task.Factory.StartNew<CompanyEntity>(() =>
{
using (var db = new JayhawkDB())
{
CompanyEntity results = null;
var query = from x in db.Companies
where x.Id == id
select x;
var record = query.FirstOrDefault<Company>();
results = new CompanyEntity
{
Id = record.Id,
CreatedById = record.CreatedById,
CreatedDT = record.CreatedDt,
DeletedById = record.DeletedById.GetValueOrDefault(),
DeletedDT = record.DeletedDt.GetValueOrDefault(),
CompanyName = record.CompanyName,
Abbreviation = record.Abbreviation,
Notes = record.Notes
};
return results;
});
}
}
The caller await s this code, not the other way around.
Oh, and that try/catch block is pretty much useless if all you're going to do is catch all Exceptions and just re-throw them.
System.ItDidntWorkException: Something didn't work as expected.
C# - How to debug code[ ^].
Seriously, go read these articles.
Dave Kreskowiak
|
|
|
|
|
Ya know... I thought of that and then thought "Gee that doesn't look right"
Well duh
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
I need to know the key that is currently pressed in a C# WPF application, so:
List<Key> PressedKeys = new List<Key>();
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (!PressedKeys.Contains(e.Key))
{
PressedKeys.Add(e.Key);
txtKeysDown.Text = String.Join(", ", PressedKeys);
}
}
private void Window_KeyUp(object sender, KeyEventArgs e)
{
PressedKeys.Remove(e.Key);
txtKeysDown.Text = String.Join(", ", PressedKeys);
}
This works, sort of. However, it does not give me the raw input from the keyboard so when AltGr is pressed it canges from Key.RightAlt => Key.LeftCtrl + Key.RightAlt whitch is Windows interpretation according to this: AltGr key - Wikipedia[^]. I dont want this, as I want the user to be able to "bind" any key to a spesific action.
So I tried to use the user32.dll call:
[DllImport("user32.dll", EntryPoint = "GetKeyboardState", SetLastError = true)]
private static extern bool NativeGetKeyboardState([Out] byte[] keyStates);
private static bool GetKeyboardState(byte[] keyStates)
{
if (keyStates == null)
throw new ArgumentNullException("keyState");
if (keyStates.Length != 256)
throw new ArgumentException("The buffer must be 256 bytes long.", "keyState");
return NativeGetKeyboardState(keyStates);
}
private static byte[] GetKeyboardState()
{
byte[] keyStates = new byte[256];
if (!GetKeyboardState(keyStates))
throw new Win32Exception(Marshal.GetLastWin32Error());
return keyStates;
}
private static bool AnyKeyPressed()
{
byte[] keyState = GetKeyboardState();
return keyState.Skip(8).Any(state => (state & 0x80) != 0);
}
}
With the function:
bool MyIsKeyDown(Key key)
{
return (((byte)GetKeyboardState()[(int)key] & 0x80) & 0x80)>0;
}
and code implementation:
private void Window_KeyDown(object sender, KeyEventArgs e)
{
foreach (Key item in Enum.GetValues(typeof(Key)))
{
if (MyIsKeyDown(item))
{
if (!PressedKeys.Contains(e.Key))
{
PressedKeys.Add(e.Key);
txtKeysDown.Text = String.Join(", ", PressedKeys);
}
}
}
}
But still, windows insisted on giving me the replacement Key.RightAlt => Key.LeftCtrl + Key.RightAlt. So how do I get the key pressed on the actual keyboard?
|
|
|
|
|
|
I've been using the "Keyboard" class to get the state of my keys; apparently without any issues. e.g.
bool ok = ( Keyboard.IsKeyDown( Key.LeftShift ) || Keyboard.IsKeyDown( Key.RightShift ) );
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
That could work, but I also want it to react to a sequence of inputs like Visual Studio does. For instance, if you have selected parts of the code you can hold LeftCtrl + K, release the keys and press LeftCtrl + F, VS will format the code for you. Then KeyBoard.IsDown is not really usable.
The problem is that I need to know what happened on your keyboard before windows do changes to it.
|
|
|
|
|
"Keyboard" is a "class"; "IsDown" is only one method; I didn't say to use it; it was an example.
Anyway, what you're citing is a "sequence of key states" that translates into some operation; and has nothing to do with testing individual key states.
Your problem is determining / tracking intent once a key is pressed.
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
|
I'd have to say this smells badly of spam - it's a limited trial of a paid-for app, and you've been here long enough to know that is the kind of thing that attracts "spam" and "spammer" votes and gets your account closed. Particularly when it's a "special promo" for CodeProject as the link implies.
I don't think spam was your intention, but I'd strongly suggest that you remove the link before it gets reported in S&A and you get kicked out.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Doesn't look like it is in the stage of getting feedback for the first time. I suggest you look for feedback from your current userbase
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Hi All
i am trying to populate a graph from a datagridview
(Not sure if this is the best practice)
i am using a sql pivot script that populates the correct data into the datagrid
It is showing the years (last 3) in column 0 and 12 months starting from column 1.
How do i show 3 series (for the years) and the 12 months on X and the value of each month on Y.
Below my code
Thank you very much
private void DoGraph(string Title)
{
string ConString = CString;
string CmdString = string.Empty;
using (SqlConnection con = new SqlConnection(ConString))
{
dataGridViewYears.DataSource = null;
CmdString = " SELECT *" +
" FROM(" +
" SELECT" +
" year(Date) as [year], left(datename(month, date), 3) as [month]," +
" SalesCatRoom as YearSales" +
" FROM tblBudgetMaster" +
" WHERE DATEPART(yy, date) >= 2015 AND DATEPART(yy, date) <= 2017" +
" ) as s" +
" PIVOT" +
" (" +
" SUM(YearSales)" +
" FOR[month] IN(jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec)" +
" )AS pvt";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Years");
dt.Dispose();
sda.Fill(dt);
dataGridViewYears.DataSource = dt.DefaultView;
dataGridViewYears.AutoResizeColumns();
con.Close();
chart1.Titles.Clear();
ChartArea chartArea1 = new ChartArea();
chartArea1.AxisX.MajorGrid.LineColor = Color.LightGray;
chartArea1.AxisY.MajorGrid.LineColor = Color.LightGray;
chartArea1.AxisX.LabelStyle.Font = new Font("Arial", 8);
chartArea1.AxisY.LabelStyle.Font = new Font("Arial", 8);
chart1.ChartAreas.Add(chartArea1);
chart1.Series.Add(new Series());
chart1.Series[0].XValueMember = dataGridViewYears.Columns[0].DataPropertyName;
chart1.Series[1].XValueMember = dataGridViewYears.Columns[0].DataPropertyName;
chart1.Series[0].YValueMembers = dataGridViewYears.Columns[2].DataPropertyName;
chart1.Series[1].YValueMembers = dataGridViewYears.Columns[3].DataPropertyName;
chart1.DataSource = dataGridViewYears.DataSource;
chart1.Series[0].Name = "Budget";
chart1.Series[1].Name = "Actual";
chart1.Series[0].Label ="#VALY";
chart1.Series[0].SmartLabelStyle.Enabled = true;
chart1.Series[1].Label = "#VALY";
chart1.Series[1].SmartLabelStyle.Enabled = true;
chart1.Size = new Size(1000, 450);
chart1.Titles.Add(Title);
chartArea1.Position.Height = 80;
}
}
}
|
|
|
|
|
So ... what is your question now ?
|
|
|
|
|
Hi Ralf
How do I show 3 series (for the years) and the 12 months on X and the value of each month on Y?
Data from datagridview - 3 rows
Thank you
|
|
|
|
|
You should be using the "data table" to create your chart series; not the "data grid".
Charting and "data grid viewing" are "parallel" operations on the same data source; one does not follow the other.
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
In Visual C#, I made a user control, which contains several separate "individual" properties. But I would like to make it into one. In which there is a plus sign in font of my property where users could click on it and expand it and access its members. Just like the property Location, Size, or Font.
I tried packaging all those properties into one class and use the class as the property type, but then I have no idea how to get or set the values! And the property just return the whole class as the value! There is NO plus sign for anybody to click!
PLEASE help me out! Thank you very VERY much! God bless you!!!
|
|
|
|
|
|
|
|
Hi,
I have defined a combobox inside a DataTemplate.
I would like to access the selected item through the SelectedItemChanged event.
Problem: the comboBox seems to be not accessible from code behind.
Could someone tell me how to proceed?
RV
xaml:
<groupbox grid.row="1" grid.column="0" background="Transparent" margin="2,0,5,0">
<groupbox.header>
On going actions list view
<dockpanel grid.row="1" background="Transparent">
<datagrid name="dataGridActionsToPerform" autogeneratecolumns="False"
="" background="Transparent" borderbrush="Transparent">
<datagrid.resources>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GridViewColumnHeader}">
<Border Name="Border"
BorderThickness="0,0,0,1"
BorderBrush="Gainsboro"
CornerRadius="4,4,0,0"
Margin="2,0">
<TextBlock x:Name="ContentHeader"
Text="{TemplateBinding Content}"
Padding="5,5,5,0"
Width="{TemplateBinding Width}"
TextAlignment="Center">
</textblock>
</border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="True">
<Setter TargetName="Border"
Property="Background" Value="LightGray">
</setter>
</trigger>
</controltemplate.Triggers>
</controltemplate>
</setter.Value>
</setter>
<Setter Property="OverridesDefaultStyle" Value="True" />
<Setter Property="Foreground" Value="Black" />
<Setter Property="FontFamily" Value="Segoe UI" />
<Setter Property="FontSize" Value="12" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border x:Name="Border" SnapsToDevicePixels="true">
<GridViewRowPresenter VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>
<Border.Style>
<Style TargetType="Border">
<Style.Triggers>
<DataTrigger Binding="{Binding ColorProperty}" Value="Black">
<Setter Property="Background" Value="Blue"/>
</datatrigger>
<DataTrigger Binding="{Binding ColorProperty}" Value="Red">
<Setter Property="Background" Value="Red"/>
</datatrigger>
</style.Triggers>
<datagrid.columns>
<datagridtextcolumn header="Actions"
="" width="220" binding="{Binding ActionName}">
<datagridtemplatecolumn header="Control"
="" width="50">
<datagridtemplatecolumn.celltemplate>
<datatemplate>
<combobox name="ControlActionComboBox"
="" itemssource="{Binding CollectionOfPictures, Mode=TwoWay}" selectionchanged="controlAction_SelectionChanged" selecteditem="{Binding SelectedItem, Mode=TwoWay}">
<combobox.itemcontainerstyle>
<Setter Property="Padding" Value="5"/>
<Setter Property="BorderBrush" Value="LightGray"/>
<Setter Property="BorderThickness" Value="1"/>
<combobox.itemtemplate>
<datatemplate>
<dockpanel>
RV
|
|
|
|
|
Your question is incongruent.
The simplest explanation is that the "code behind" you are "probably" looking for is wired to the following event handler:
SelectionChanged="controlAction_SelectionChanged"
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
Thank you Gerry for your reply,
Actually I had in mind to do a treatment, depending on the selected item. For that purpose, it is essential to determine which item was selected from controlActionComboBox.
But in the code behind I cannot address this comboBox through its name. That's the issue.
And I cannot figure out how to do what I have in mind.
Best regards,
RV
|
|
|
|
|
You can't wire up to an item in your DataTemplate directly. That's not the way that DataTemplates work. You'll need to do something like this[^] and then add the event handlers.
This space for rent
|
|
|
|
|
Thank you Pete for your reply,
I've finally got the solution to this issue through:
string text = (((sender as ComboBox).SelectedItem) as ActionPicture).ImageName
Where ActionPicture is the picture enclosed in the selected. And ImageName is the name of that picture.
Best regards,
Rv
|
|
|
|