Tuesday, February 11, 2014 by Nate Bross
Someone asked on Stack Overflow:
Ok, I have an old batch file that does exactly what I need. However, with out new administration we can’t run the batch file anymore so I need to start up with C#.
I’m using Visual Studio C# and already have the forms set up for the application I need to build. (I’m learning as I go)
Here is what I need to accomplish in C# (This is the batch guts)
sqlcmd.exe -S .\PDATA_SQLEXPRESS -U sa -P 2BeChanged! -d PDATA_SQLEXPRESS -s ; -W -w 100 -Q "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = '%name%' "
Basically it uses SQLCMD.exe with the already existing datasource called PDATA_SQLExpress.
I’ve searched and gotten close but I’m still at a loss on where to start.
I posted the following answer, which was chosen as the accepted answer and received 184 upvotes:
To execute your command directly from within C#, you would use the SqlCommand class.
Quick sample code using paramaterized SQL (to avoid injection attacks) might look like this:
string queryString = "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = @tPatSName";
string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;User Id=sa;Password=2BeChanged!;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("@tPatSName", "Your-Parm-Value");
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
Notable comments
Nate (5 upvotes): @Fa773NM0nK No good reason beyond its a sample and I forgot. For anyone wondering, here’s a good read on why its a good idea: stackoverflow.com/questions/3386770/using-on-sqldatareader
Fa773N M0nK (6 upvotes): Is there any reason for the using on SqlConnection but not on SqlDataReader?
Nate (0 upvotes): @Anjali Yes you can call SqlCmd.exe directly from C#, you would need to look into Process.Start()
Nate (0 upvotes): @Redracer68 Why would you want OdbcCommand? If your database is SQL Server, the SqlCommand (and SqlConnection) are the best classes to use; while you can access SQL Server via OdbcCommand and even OleDbCommand the SqlCommand is probably best. What’s your usecase for using ODBC instead? That said, you could switch the above code to OdbcConnection and OdbcCommand setup an ODBC DSN and I don’t see why it would not work.
Nate (1 upvotes): @Redracer68 I suspect an issue with the SQL query. Try using the name of the table in your query, TPatientRaw instead of the full [dbo].[Table]
Originally posted on Stack Overflow — 184 upvotes (accepted answer). Licensed under CC BY-SA.
Tuesday, September 24, 2013 by Nate Bross
Someone asked on Stack Overflow:
I was just doing a bit of Visual Studio 2012 for Windows Phone 8, but when I started typing Click="" in the .xaml file, no thing showed up in a dropdown list. It used to show up but now it isn’t!
I posted the following answer, which was chosen as the accepted answer:
Have you tried restarting your computer? That often fixes these types of issues (sometimes just restart Visual Studio does the trick).
That said, you can always generate your own event handlers. Intellisense is great; but not having it should not cripple you. The below should work, adjusting for your button name.
//code-behind
private void btnYourButton_Click(object sender, EventArgs e)
{
//do stuff
}
<!--xaml-->
<Button x:Name="btnYourButton" Click="btnYourButton_Click"/>
Originally posted on Stack Overflow — 0 upvotes (accepted answer). Licensed under CC BY-SA.
Friday, September 20, 2013 by Nate Bross
Someone asked on Stack Overflow:
I have build an app using Visual Studio 2012 for Windows Phone and when I started developing I selected Windows Phone 8.0 as target.
Now that the app has been deployed I have customers asking to provide a 7.5 version. Is there a way to “downgrade” the target of a project in Visual Studio 2012?
I have checked some questions here that talk about supporting both 7.5 and 8 but none is about downgrading an existing project.
I posted the following answer, which was chosen as the accepted answer and received 3 upvotes:
You will need to install the Windows Phone 7.1 SDK (Which is to consumers v7.5). You’ll also need to create a new Project and target Windows Phone 7.1.
If you are not using Windows Phone 8 exclusive APIs, you can probably just “Add As Link” all the files in your Windows Phone 8 project to the Windows Phone 7.1 project and just re-compile. Even if you are, you can still use this approach, you will just need to use compiler directives to fix whatever API issues you find at compile time.
Here is an article that explains the different ways to target both WP7.1 and WP8. The one I’m suggesting is the last in this list: How to target multiple versions with your app for Windows Phone
Notable comments
Nate (0 upvotes): That is correct. You will need one project per “output” type, in this case, WP7 and WP8. Like I said though, that doesn’t necessarily mean fully duplicate code though.
Originally posted on Stack Overflow — 3 upvotes (accepted answer). Licensed under CC BY-SA.
Friday, September 6, 2013 by Nate Bross
Someone asked on Game Development:
I want to know if there is an easy way to render sprites in XNA inside other sprites or something similar (I don’t know if sprite is the best or unique way to draw in XNA). For example, I want to draw an object called SCENE that defines a rectangle. Inside the rectangle there are some SQUARES. I’d like to code something to draw all the SQUARES when the SCENE are draw. At the same time, if I draw the SQUARES on the SCENE, the movement of the SQUARES are limited by the SCENE size.
Is this possible in XNA?
I did this with Pygame and is very easy to make.
Thanks in advance.
I posted the following answer, which was chosen as the accepted answer and received 1 upvote:
The way that you would do this would be to use the power of C# and create some objects.
You would create a Scene object, that would have a Square object, which internally would have a collection of Squares inside it.
The .Draw() method of Scene would know it had to draw its own background, as well as tell the Square object to draw itself and all its children.
This is relatively easy with C#, extremely common, and probably the most simple way to do what you just mentioned in your post. A quick sample you might start with:
public class Scene
{
public Texture2D background;
public SquareList Square;
public class SquareList : List<Square>
{
List<Square> Items;
public void Draw(SpriteBatch batch)
{
foreach(var item in items)
{
// store position of each item instead of hardcode
batch.Draw(item, new Vector2(0,0), Color.White);
}
}
}
public class Square
{
Texture2D myTexture;
}
public void Draw(SpriteBatch batch)
{
batch.Draw(background, new Vector2(0,0), Color.White);
Square.Draw(batch);
}
}
In this case, containment seems to make the most since, but you may want to have some of your objects inherit from a common base, such as “Sprite” or similar. It is beyond the scope of a single answer on this site to explain all of that. I recommend that you review some of the XNA sample code and see how they do things, and come back and ask us specific questions when you get stuck.
Originally posted on Game Development — 1 upvotes (accepted answer). Licensed under CC BY-SA.
Tuesday, August 20, 2013 by Nate Bross
I asked this on Database Administrators:
I have some databases created using Entity Framework Code First; the apps are working and in general I’m pretty happy with what Code First lets me do. I am a programmer first, and a DBA second, by necessity. I am reading about DataAttributes to further describe in C# what I want the database to do; and my question is: what penalty will I be eating by having these nvarchar(max) strings in my table (see example below)?
There are several columns in this particular table; in C# they are defined as such:
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string Name { get; set; }
public string Message { get; set; }
public string Source { get; set; }
public DateTime Generated { get; set; }
public DateTime Written { get; set; }
I expect to query and/or sort based on Name, Source, Generated, and Written. I expect Name and Source to be in the 0-50 character length, occasionally up to 150. I expect this table to start pretty small (<100k rows), but grow significantly over time (>1m rows). Obviously message could be small or large, and will probably not be queried against.
What I want to know, is there a performance hit for my Name and Source columns being defined as nvarchar(max) when I never expect them to be larger than 150 characters?
ConcernedOfTunbridgeWells answered (29 upvotes):
Larger nvarchar (max) data items (over 8000 bytes or so) will spill over into text storage and require additional I/O. Smaller items will be stored in-row. There are options that control this behaviour - see this MSDN article for more details.
If stored in-row there is no significant I/O performance overhead; there may be additional CPU overhead on processing the data type but this is likely to be minor.
However, leaving nvarchar (max) columns lying around the database where they are not needed is rather poor form. It does have some performance overhead and often data sizes are quite helpful in understanding a data table - for example, a varchar column 50 or 100 chars wide is likely to be a description or a free-text field where one that’s (say) 10-20 chars ling is likely to be a code. You would be surprised how much meaning that one often has to infer from a database through assumptions like this.
Working in data warehousing, as often as not on poorly supported or documented legacy systems, having a database schema that’s easy to understand is quite valuable. If you think of the database as the application’s legacy, try to be nice to the people who are going to inherit it from you.
Notable comments
Nate (0 upvotes): I know it does hurt performance. When I define my own tables with SQL I use varchar(n). My question was more about how much it hurts performance(though I realize as posted that wasn’t explicitly clear).
Martin Smith (5 upvotes): Looks like you need to apply either [MaxLength] or [StringLength] attributes. Some additional possible negative factors of too wide columns are mentioned in @PaulWhite’s answer here
Originally posted on Database Administrators — 35 upvotes. Licensed under CC BY-SA.
Thursday, July 18, 2013 by Nate Bross
Someone asked on Stack Overflow:
I’m trying to change the value of an asp:textbox using jQuery using this line of code that I’ve found referenced in several places:
$("#<%= element.ClientID %>").attr('value', "");
However, I keep getting a syntax error saying that the first part is an invalid expression. I’m sure it’s something simple I’m missing here, just don’t know what it is.
jQuery is linked via the master page and the .js file with the function containing the line in question is individually linked on the specific page.
I posted the following answer, which was chosen as the accepted answer and received 1 upvote:
Your syntax is correct:
$('#<%= textbox.ClientID%>').val('new textbox value');
is the correct syntax for selecting an <asp:textbox /> via javascript and in this case jQuery; however, this only works in .ASPX files.
You will need to convert this separate .js file to an in-line script in your .ASPX page for this to work.
Alternatively, you could use a CSS class as a selector, which will work from your external .js file:
In your .JS file
$('.uniqueCSSClassName').val('new textbox value');
In your .ASPX file
<asp:textbox ID="whatever" CssClass="uniqueCSSClassName" />
This will allow you to select your text box from an external javascript file. This is not a pretty approach, but it will work. I would go for the first option, and move my .js code into an inline script.
Originally posted on Stack Overflow — 1 upvotes (accepted answer). Licensed under CC BY-SA.
Wednesday, June 26, 2013 by Nate Bross
Someone asked on Stack Overflow:
Is it possible to get my devices DPI from c# using a native win api call?
I know how to get the dpi from a windows forms application and the current code I have is:
Graphics g = Graphics.FromImage(new Bitmap(10, 10));
var scaleX = g.DpiX / 96.0f;
var scaleY = g.DpiY / 96.0f;
I was wondering if the is a win api call that can make things easier.
I posted the following answer, which was chosen as the accepted answer and received 2 upvotes:
What about a WMI Query to the Win32_DesktopMonitor class?
PixelsPerXLogicalInch
Data type: uint32
Access type: Read-only
Qualifiers: Units (Pixels per Logical Inch)
Resolution along the x-axis (horizontal direction) of the monitor.
PixelsPerYLogicalInch
Data type: uint32
Access type: Read-only
Qualifiers: Units (Pixels per Logical Inch)
Resolution along the y-axis (vertical direction) of the monitor.
You might use it similar to this question:
ManagementObjectSearcher monitorObjectSearch = new ManagementObjectSearcher("SELECT * FROM Win32_DesktopMonitor");
foreach (ManagementObject monitor in monitorObjectSearch.Get())
{
Debug.WriteLine(monitor["PixelsPerXLogicalInch");
Debug.WriteLine(monitor["PixelsPerYLogicalInch");
}
There is also the Windows API Route with GetDeviceCaps, but I’ve read that there are some issues with it on Windows 7 so your mileage may be different.
There is also the Direct2D GetDesktopDpi (mentioned by Alex), which looks like it would require doing some COM Interop calls, and may or may not be as clean and will only work Windows versions where Direct2D is available. Some additional information on Direct2D and .NET.
Originally posted on Stack Overflow — 2 upvotes (accepted answer). Licensed under CC BY-SA.
Friday, December 28, 2012 by Nate Bross
Someone asked on Stack Overflow:
I am using session to do two things:
- Keep track of which css file to load for a particular company.
- Keep track of the Company Id Guid that tracks what company we are in.
I am seeing that this is coming in as null sometimes but I’m not getting a consistent problem to track down. I have no doubt this is probably something in my code that I need to track down but this bring me up to my questions about session…
- Am I relying on Session to much to pass information between screens?
- Is it consistent?
- What could be clearing it between page loads?
- Is session easily cleared by the user?
- Should I be using something else more reliable?
I am worried that I will move this to live usage and have all kinds of problems.
I’m simply doing this:
Session["Css"] = css;
and reading it the same way:
css = Session["Css"]
UPDATE
The session I am using:
HttpSessionStateBase Controller Session
I posted the following answer, which was chosen as the accepted answer and received 4 upvotes:
There are a few types of Session State. InProc, StateServer, and SqlServer. I believe the default is InProc. You can read more about this on MSDN here and here.
Each of these will obey the timeout value for sessionState defined in your web.config file. For a single server setup (which is what I typically do) I usually have my sessionState setup as follows:
<sessionState
mode="StateServer"
stateConnectionString="tcpip=127.0.0.1:42424"
timeout="2880" />
This is the same default timeout as Forms Auth, so my sessions will stick around as long as my users auth cookie/session. This will require you to set the start up on the ASP.NET State Server to Automatic. Below is my high-level pass at explaining the types and their potential drawbacks.
InProc
This will be reset everytime the application pool recycles the worker process for the web app. I believe this is what is happening to you, and this is why your session variables are null at what appear to be random times.
StateServer
This will persist state across apppool recycles, but requires that you enable the ASP.NET State Server Service, and change it’s start up type to Automatic.
You can run into issues if you have a web farm or multiple web servers handling the website, unless you run a dedicated state server.
This requires that variables stored in session variables are [Serializable].
SQLServer
This will persist session variables to a SQL database, and is is generally the best approach for a web farm situation.
This requires that variables stored in session variables are [Serializable].
Notable comments
Nate (0 upvotes): @ErocM I use them as a quick way to store things during a user’s session, such as which .css file to render, etc. I generally use cookies when both server code and javascript need them. Main reason, sessions are easy (with a state server or sql server, they persist). I have never had any problems. That said, others have said they have issues with them, and never use them. Maybe their sites are bigger and used more than mine and stress the session state to its limit, I don’t know. I know that I use them. The app I’m working on now uses 3 session variables, so I guess I use them sparingly.
Originally posted on Stack Overflow — 4 upvotes (accepted answer). Licensed under CC BY-SA.
Friday, December 21, 2012 by Nate Bross
Someone asked on Server Fault:
After updating a Windows XP SP3 machine to Citrix Receiver v3.3, the user is unable to launch any published applications. The error they got is:
No value could be found for (Allowhotkey) that satisfies all lockdown requirements.
I posted the following answer, which was chosen as the accepted answer and received 1 upvote:
I struggled with this for quite a while, and I eventually found a solution which involves disabling Citrix Lockdown. I found several link-bait-sites, which were of no use, and a few posts recommending a uninstall and re-install, which did not help.
Eventually after a lot of searching and finding garbage, I found this post on the Citrix Forums by Simon Burbery. In it, he recommends changing all of the EnableLockdown values from 1 to 0.
- Export HKLM\Software\Citrix to a reg file
- Find any
EnableLockdown values (there are a few) and change from 1 to 0
- Import the modified reg file
- Exit Receiver completely
- Launch Published App
I found about three of these values. I simply did a CTRL + F in regedit and changed the ones I found and restarted the receiver. I have yet to discover and side effects of this method yet.
Originally posted on Server Fault — 1 upvotes (accepted answer). Licensed under CC BY-SA.
Tuesday, November 13, 2012 by Nate Bross
Someone asked on Stack Overflow:
I have a user object, which has three bits of data, the user, their subscription level and a list of all groups that they ARE or COULD be a member of. I need to generate a view that lets me edit this data in a smart way and I want it to be tied to my strongly typed model.
I would like to have one check box for each possible group, and allow the user of my app to check or uncheck boxes to change membership. The problem I’m having is that my action
[HttpPost]
public ActionResult Edit(UserModel usr)
{
}
never receives the values from the checkboxes in the view, but the other properties are correctly populated.
My first view looked like this:
...
@Html.EditorFor(m => m.UserName)
@Html.EditorFor(m => m.Subscription)
@Html.EditorFor(m => m.Membership) // just displays the string and bool values
...
My second stab [also failed]
...
@Html.EditorFor(m => m.UserName)
@Html.EditorFor(m => m.Subscription)
@foreach(var itm in Model.Membership)
{
@Html.EditorFor(_ => itm)
}
...
I also tried, and failed to hand craft the <input> tags without using @Html. with no luck.
This is what the UserModel looks like:
public class UserModel
{
public string UserName { get; set; }
public int Subscription { get; set; }
public Dictionary<String, bool> Membership { get; set; } // this is the problem
}
I posted the following answer, which was chosen as the accepted answer:
There may be a better way to solve this, but I ended up switching from Dictionary<String,Bool> to a List<SelectListItem>
The view code that generates correct post data is as follows:
...
<ul>
@for (int i = 0; i < Model.Membership.Count; i++ )
{
<li>
@Html.HiddenFor(_ => Model.Membership[i].Text)
@Html.HiddenFor(_ => Model.Membership[i].Value)
@Html.CheckBoxFor(_ => Model.Membership[i].Selected) @Model.Membership[i].Text
</li>
}
</ul>
...
Originally posted on Stack Overflow — 0 upvotes (accepted answer). Licensed under CC BY-SA.