Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
Queen of Beans
Jun 15, 2007

This Post Sucks posted:

Alright, I've got another newbie question, although this may relate more to Visual Studio 2010.

We're currently in the process of (slowly) updating our site from classic ASP to .Net. The plan of operation is to start with high impact action pages (form handlers, ect) then move on to user facing pages.

Now, I'm trying to figure out the best way to do this. What I am currently doing is I've got a new .Net directory (with it's on AppPool, ect) that runs parallel to the Classic ASP one. Both are at the same level on the hierarchy. Inside my new .Net directory I'm mirroring the file structure, just replacing the .asp files with updated .aspx files.

The problem I'm running in to is since the new .Net directory isn't (or wasn't created as one in the first place) a project, it's just basically a repository for .net files and their code behinds, I'm finding it difficult (impossible) to correctly link Namespaces and Classes.

Is there anyway that I can either: A) link up the namespaces/classes to what I have currently or B) convert the new .Net directory to a Project?

I'm close enough to the beginning of this process that I can start from scratch if I need to, so there's that at least.

Thanks!

Just create a new project and add the files to it. Then sort everything out properly. Do it now, before the project becomes a massive behemoth that is really hard to change. Better to have a little halt in real development now than to run into potentially massive problems and an awful codebase later.

Adbot
ADBOT LOVES YOU

This Post Sucks
Dec 27, 2004

It Gave Me Splinters!

hobofood posted:

Just create a new project and add the files to it. Then sort everything out properly. Do it now, before the project becomes a massive behemoth that is really hard to change. Better to have a little halt in real development now than to run into potentially massive problems and an awful codebase later.

Yeah, after I posted that I found the "Create Project from Existing Code" option and I think that took care of what I needed. Thanks!

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

This Post Sucks posted:

Alright, I've got another newbie question, although this may relate more to Visual Studio 2010.

We're currently in the process of (slowly) updating our site from classic ASP to .Net. The plan of operation is to start with high impact action pages (form handlers, ect) then move on to user facing pages.

Now, I'm trying to figure out the best way to do this. What I am currently doing is I've got a new .Net directory (with it's on AppPool, ect) that runs parallel to the Classic ASP one. Both are at the same level on the hierarchy. Inside my new .Net directory I'm mirroring the file structure, just replacing the .asp files with updated .aspx files.

The problem I'm running in to is since the new .Net directory isn't (or wasn't created as one in the first place) a project, it's just basically a repository for .net files and their code behinds, I'm finding it difficult (impossible) to correctly link Namespaces and Classes.

Is there anyway that I can either: A) link up the namespaces/classes to what I have currently or B) convert the new .Net directory to a Project?

I'm close enough to the beginning of this process that I can start from scratch if I need to, so there's that at least.

Thanks!

[edit]
Already answered!

Here's something you might have to think about : Does your site use Session data at all? If so, you're going to have to pass the session data back and forth between the classic ASP site and the .NET site.

New Yorp New Yorp fucked around with this message at 20:32 on Mar 6, 2012

Fastbreak
Jul 4, 2002
Don't worry, I had ten bucks.
For those of you that have worked with RavenDB, I am stumped on something that I am sure must be simple and I am goofing it.

I am doing a proof of concept with the blog structure here: http://ayende.com/blog/4466/that-no-sql-thing-modeling-documents-in-a-document-database

I figured it would be a good example since we have a very simple blog site in the office and this would be a cool way to show some of the simple stuff we do. I got a list of sprocs our other site does and was going to show a speed comparison. For a while it was going good, but one request I can't seem to get to work and it SHOULD be easy.

One thing that the current blog site does is get the most popular posts (most comments) by category. I tried just focusing on getting the most commented posts back, but even that doesn't work returning posts with only 9 comments when I know there are some with 30 or more. Though the sort is doing SOMETHING since when I orderby ascending, it returns posts with 0 or 1 comments. I tried just getting posts that have a certain category and that seems to work, but how do I sort by a child collections?

Some code:
code:
public class Post
{
    public string Id { get; set; }
    public string UserID { get; set; }
    public string BlogID { get; set; }
    public string PostContent { get; set; }
    public string Title { get; set; }
    public DateTime PostDate { get; set; }
    public List<Comment> Comments { get; set; }
    public List<String> Categories { get; set; }

	public Post()
	{
        Comments = new List<Comment>();
        Categories = new List<String>();
	}
}
code:
 var posts = session.Query<Post>()
                       .Where(post => post.Categories.Any(category => category == Cat))
                       .OrderByDescending(post => post.Comments.Count);

This Post Sucks
Dec 27, 2004

It Gave Me Splinters!

Ithaqua posted:

[edit]
Already answered!

Here's something you might have to think about : Does your site use Session data at all? If so, you're going to have to pass the session data back and forth between the classic ASP site and the .NET site.

Yes it does use Session data and I was planning to pass stuff back and forth. Is this going to cause a problem with the .NET stuff being sequestered like this?

Sab669
Sep 24, 2009

A few more newbie questions :downs:

I'm trying to loop through a folder and display all of the images in it. Then, I'd like each image to be clickable so that when it is clicked it'll automatically download the file.

code:
string[] fileEntries = Directory.GetFiles(Server.MapPath("~/Images"));
            ImageButton[] buttons = new ImageButton[fileEntries.Length];
            int i = 0;

            foreach (string file in fileEntries)
            {
                buttons[i] = new ImageButton();
                buttons[i].ImageUrl = file;
                //buttons[i].Click += new ImageClickEventHandler(imageDownLoad);
                i++;
                
            }
That's what I have, but the ImageButtons don't actually show up on the page.
Also I'm having issues with that line I commented out as well. It gives the error, "No overload for imageDownload matches delegate System.Web.UI.ImageClickEventHandler" but the first issue of them not showing up is a bit more critical at the moment.

Fastbreak
Jul 4, 2002
Don't worry, I had ten bucks.

Sab669 posted:

A few more newbie questions :downs:

I'm trying to loop through a folder and display all of the images in it. Then, I'd like each image to be clickable so that when it is clicked it'll automatically download the file.

code:
string[] fileEntries = Directory.GetFiles(Server.MapPath("~/Images"));
            ImageButton[] buttons = new ImageButton[fileEntries.Length];
            int i = 0;

            foreach (string file in fileEntries)
            {
                buttons[i] = new ImageButton();
                buttons[i].ImageUrl = file;
                //buttons[i].Click += new ImageClickEventHandler(imageDownLoad);
                i++;
                
            }
That's what I have, but the ImageButtons don't actually show up on the page.
Also I'm having issues with that line I commented out as well. It gives the error, "No overload for imageDownload matches delegate System.Web.UI.ImageClickEventHandler" but the first issue of them not showing up is a bit more critical at the moment.

I imagine from glancing at that, that the url returned is a file path instead of a url to the image. Check the image url being returned from your function?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Sab669 posted:

A few more newbie questions :downs:

I'm trying to loop through a folder and display all of the images in it. Then, I'd like each image to be clickable so that when it is clicked it'll automatically download the file.

code:
string[] fileEntries = Directory.GetFiles(Server.MapPath("~/Images"));
            ImageButton[] buttons = new ImageButton[fileEntries.Length];
            int i = 0;

            foreach (string file in fileEntries)
            {
                buttons[i] = new ImageButton();
                buttons[i].ImageUrl = file;
                //buttons[i].Click += new ImageClickEventHandler(imageDownLoad);
                i++;
                
            }
That's what I have, but the ImageButtons don't actually show up on the page.
Also I'm having issues with that line I commented out as well. It gives the error, "No overload for imageDownload matches delegate System.Web.UI.ImageClickEventHandler" but the first issue of them not showing up is a bit more critical at the moment.

You're not adding the ImageButtons to any controls on your page. As for the event handler, read this. Your event handler method needs to have two parameters of type object and ImageClickEventArgs.

Also, don't make an array of ImageButtons, arrays are so 2001. Use a List<ImageButton>.

Sab669
Sep 24, 2009

Looking through a breakpoint, it says buttons[0]'s ImageUrl = "E:\\MyProject\\Images\\Image1.jpg", so that would be correct, right?

e; or should it simply just be Images\\Image1.jpg?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Sab669 posted:

Looking through a breakpoint, it says buttons[0]'s ImageUrl = "E:\\MyProject\\Images\\Image1.jpg", so that would be correct, right?

e; or should it simply just be Images\\Image1.jpg?

It needs to be a path relative to your web server. If I go to https://www.yoursite.com how is my computer supposed to deal with the page telling me to load E:\myproject\images\image1.jpg? I don't even have an E: drive!

This Post Sucks
Dec 27, 2004

It Gave Me Splinters!
Ok, one last (hopefully) quick question.

I've converted my code over to a project and since I did, I'm having one of my methods of a class I've created not able to be seen.

Here's the class:

code:
namespace sfClasses
{
    namespace SQL
    {
        public class sqlDataSet
        {
            string myString;
            SqlConnection myConnection;

            public sqlDataSet(string inputString, SqlConnection inputConnection)
            {
                myString = inputString;
                myConnection = inputConnection;
            }

            public DataTable returnData()
            {
                DataTable sqlMyReader = new DataTable();
                //SqlCommand myCommand = new SqlCommand(myString, myConnection);
                SqlDataAdapter myAdapter = new SqlDataAdapter(myString, myConnection);

                myAdapter.Fill(sqlMyReader);

                return sqlMyReader;

            }

           
            public bool setData()
            {
                SqlCommand mySet = new SqlCommand();
                mySet.CommandType = CommandType.Text;
                mySet.CommandText = myString;
                mySet.Connection = myConnection;

                myConnection.Open();
                mySet.ExecuteNonQuery();
                myConnection.Close();
                return true;
            }

            ~sqlDataSet()
            {
            }
        }
    }
}
Here's the call:
code:
bool updateAcct = new sqlDataSet(myQuery, myConnection).setData();
I'm getting the error of:
'sqlDataSet' does not contain a definition for 'setData' and no extension method 'setData' accepting a first argument of type 'sqlDataSet' could be found (are you missing a using directive or an assembly reference?)

Now, if I remove the namespace include and then copy/paste the class (renaming it) to the same code behind file it works fine.

Another thing I've noticed is that while the "returnData" method is working, if I rename it, Visual Studio doesn't pick up the changes and doesn't throw errors.

I've tried clean rebuilds of both the solution and the project.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

This Post Sucks posted:

:words:

I'm getting the error of:
'sqlDataSet' does not contain a definition for 'setData' and no extension method 'setData' accepting a first argument of type 'sqlDataSet' could be found (are you missing a using directive or an assembly reference?)

Now, if I remove the namespace include and then copy/paste the class (renaming it) to the same code behind file it works fine.

Another thing I've noticed is that while the "returnData" method is working, if I rename it, Visual Studio doesn't pick up the changes and doesn't throw errors.

I've tried clean rebuilds of both the solution and the project.

Do you have a using directive at the top of the file where you're trying to use your class?

This Post Sucks
Dec 27, 2004

It Gave Me Splinters!

Ithaqua posted:

Do you have a using directive at the top of the file where you're trying to use your class?

Yep, and the Intellisense is picking it up.

code:
using sfClasses.SQL;
I should have mentioned, the "returnData" method is working just fine, it's the "setData" one that's not being found. Intellisense is picking up the "returnData" method also, but doesn't pick up any changes in the method name.

Sab669
Sep 24, 2009

Yea, that was dumb of me Ithaqua. I'm not sure why I thought it'd work :v:

I was able to just Subtract 0 - n so that it was only putting in Images\\Image1.jpg into the ImageUrl, then added that to a control on the page and it worked now.

Now to iron out this issue of not being able to set the OnClick in the code...

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

This Post Sucks posted:

Yep, and the Intellisense is picking it up.

code:
using sfClasses.SQL;
I should have mentioned, the "returnData" method is working just fine, it's the "setData" one that's not being found. Intellisense is picking up the "returnData" method also, but doesn't pick up any changes in the method name.

It's going to be pretty much impossible for us to figure it out without seeing more of how you're trying to reference your code.

A few pointers, though:

1) Namespaces, class names, and method names should be UpperCamelCase.
2) You can do
code:
namespace SfClasses.Sql 
{
...
}
to reduce nesting
3) Don't use a finalizer unless you're releasing unmanaged resources. In general, don't even bother putting them in your classes. It's useless code if it's empty.
4) Passing around SqlConnections is going to end up biting you eventually, whether it's due to the connection getting disposed when you weren't expecting it to be disposed, or accidentally leaving a connection open. Create a new SqlConnection in a using block so that you know that it only exists for the lifetime of the query that's being executed.

fryzoy
Sep 21, 2005
What.
Greets.

My problem stems from two technologies playing together: .NET with the CLR and Stackless Python (SLP). SLP works off the premise of switching between multiple stacks to fully utilize a single thread. Basically, the active stack gets changed if a Python or C function decides that it is going to block and wait for a signal, yield or sleep. When this happens, SLP switches the active stack by copying the current stack into a heap-allocated block of memory and copying the stored stack of the next tasklet to run over the previous stack.

Now, what I have is managed .NET functions (C#) getting called from unmanaged code that is running inside such a tasklet. That means, if my .NET code calls a Python function that blocks, my .NET stack will also get serialized and copied away. This works fine until I add other .NET system threads into the game: If my main SLP thread is currently executing another piece of code that is not in my .NET tasklet, and a different .NET thread invokes the garbage collector for whatever reason (be it memory pressure or forced), the CLR terminates due to stack corruption. Through meticulous debugging with WinDBG, IDA and the CLR 2.0 source I have determined that this is because when the GC is invoked, the CLR tries to walk through the stack of all threads running managed code.

This is where it gets interesting: When the CLR creates a new execution frame from or to unmanaged code (and at other times), it places (among other things) a security cookie on the stack to detect stack overflows and a virtual method table pointer for the CLR Frame class. It checks the correctness of that VMT pointer and cookie every time it accesses that frame. The CLR stores a pointer to the last active frame in each thread in the thread store list.

Now when it tries to access that frame during the GC run from a non-SLP thread and runs the above mentioned checks, it fails and terminates because the frame structure, including the VMT and cookie, has been copied away into the heap somewhere. Instead the frame pointer of the thread points somewhere into the stack of the currently active SLP tasklet or above it.

When I run the GC exclusively in the SLP thread, everything works fine, and of course one solution is to just do this and never use any other threads, but I'd really like to avoid that. So what I'd need is some way to prevent the GC from running in a different thread, since I don't have much control over how SLP works (while there is a version available that does stack switching by moving the stack pointer, it is applied at compile-time and I can't recompile the current python binary).

So this is where I'm hoping anyone has any ideas to solve this or suggestions on how to alternatively deal with this. Google searches for .NET questions obviously only yield garbage, but the general consensus is that you "shouldn't have to control the GC". I don't disagree, but I don't see any other solution here. I'm definitely open to different approaches.

This Post Sucks
Dec 27, 2004

It Gave Me Splinters!

Ithaqua posted:

It's going to be pretty much impossible for us to figure it out without seeing more of how you're trying to reference your code.

It seems like my project isn't picking up any changes I do to the class period. I removed the passing of the connection string (as you suggested) and now all calls are saying it can't find a constructor that uses only one argument. Is there anything I can do to make the solution/project force refresh the class?

I've tried unloading/reloading the project. Doing clean rebuild of both the solution and projects.

Also, the passing connection string was just left over from when I didn't know how to use a web.config file :blush:

Edit: Well, I renamed all my Classes,Namespaces, and Methods to UpperCamelCase and now everything seems to be reading just fine. Strange.

Thanks for all your help!

This Post Sucks fucked around with this message at 22:58 on Mar 6, 2012

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

fryzoy posted:



Why can't you use your own build of Python? Is it an interop issue with something else?

Atimo
Feb 21, 2007
Lurking since '03
Fun Shoe

This Post Sucks posted:

Ok, one last (hopefully) quick question.

I've converted my code over to a project and since I did, I'm having one of my methods of a class I've created not able to be seen.

Here's the class:

code:
namespace sfClasses
{
    namespace SQL
    {
        public class sqlDataSet
        {
            //snip

            ~sqlDataSet()
            {
            }
        }
    }
}
-snip




What in the world is the finalizer for?

Eric Lippert posted:

quote:

When should I manually create a destructor?
Almost never.
http://stackoverflow.com/a/4899622/426894

fryzoy
Sep 21, 2005
What.

Jabor posted:

Why can't you use your own build of Python? Is it an interop issue with something else?

The application I'm interacting with won't allow me to use a custom Python version so I don't really have any control over it.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Atimo posted:

What in the world is the finalizer for?


Is it wrong that I have programmer crushes on Eric Lippert and Jon Skeet?

On the plus side, the incorrect use of finalizers (along with non-threadsafe singletons, incorrect IDisposable implementations, inline SQL, and IDisposables not wrapped in using blocks) are very useful code smells.

New Yorp New Yorp fucked around with this message at 03:09 on Mar 7, 2012

wwb
Aug 17, 2004

Fastbreak posted:

One thing that the current blog site does is get the most popular posts (most comments) by category. I tried just focusing on getting the most commented posts back, but even that doesn't work returning posts with only 9 comments when I know there are some with 30 or more. Though the sort is doing SOMETHING since when I orderby ascending, it returns posts with 0 or 1 comments. I tried just getting posts that have a certain category and that seems to work, but how do I sort by a child collections?

Some code:
code:
public class Post
{
    public string Id { get; set; }
    public string UserID { get; set; }
    public string BlogID { get; set; }
    public string PostContent { get; set; }
    public string Title { get; set; }
    public DateTime PostDate { get; set; }
    public List<Comment> Comments { get; set; }
    public List<String> Categories { get; set; }

	public Post()
	{
        Comments = new List<Comment>();
        Categories = new List<String>();
	}
}
code:
 var posts = session.Query<Post>()
                       .Where(post => post.Categories.Any(category => category == Cat))
                       .OrderByDescending(post => post.Comments.Count);

What I would do is add a readonly property to your Post class that spits out the count property. Said property will get serialized and then ravedb can query on it much more easily.

The problem you are running into is that internally ravendb has no idea what you've got in your object, it works pretty much on dynamics. Another thing to do is to look at the index it will automatically create when you run that query, you might just need to manually fix it.

Kekekela
Oct 28, 2004

Ithaqua posted:

Is it wrong that I have programmer crushes on Eric Lippert and Jon Skeet?
Lipperts amazing. I'm not a Skeet fan personally but plenty are.

Rescue Toaster
Mar 13, 2003

Kekekela posted:

Lipperts amazing.

I've learned more from his blog than I have from any of my data structures classes so far.


On a .NET/C# note... is there an easy way to automate the deploying of a WCF service to a remote IIS server, and run it with full debugging/stepping/breakpoints/object examine right in VS?

I'm looking to start in on some CUDA/OpenCL work, and rather than buy a massively expensive workstation laptop, I was thinking I might setup a VPN to a server at home with a GPU or two installed. So it seems that my options were:

1) Just remote in, and run from VS locally. Really ugly running VS through remote desktop though.
2) Code a client-server framework into my projects, like WCF. Usually pretty quick and dirty to setup if you just let WCF create the service definitions. Assuming deployment to the server can be automated as above, might work OK.
3) Somehow use Team Foundation Server? (I have msdn license for it) I know it can do automated builds and unit testing and such, but can you actually debug with code executing on the server? Any way to interact with an application? (even just console input/output)

This Post Sucks
Dec 27, 2004

It Gave Me Splinters!

quote:

Atimo posted:

What in the world is the finalizer for?

Almost never.
http://stackoverflow.com/a/4899622/426894

It was mainly left over from years ago when I did C++ coding and not knowing any better in C#! I'm just learning, ok :(

It's good to know though, so thanks!

Ok, so two questios!

For some reason I'm having issues with "Request.Cookies" inside a class as follows:

code:
using System;
using System.Collections.Generic;
using System.Web;

namespace SfClasses.AnotherClass
{
   public class Another Class
   {
        public AnotherClass()
        {
         ....
         someVariable = Request.Cookies["myCookies"];   // Error Here
         ....
        }
      ....
   }
}
With the error of: "CS0103: The name 'Request' does not exist in the current context". From everything I've seen, Request should be in System.Web, right?

Now, I did get it to work (or at least not throwing an error) using:
code:
   someVariable = HttpContext.Current.Request.Cookies["myCookies"];
but was getting some other issues after it since we're doing some stuff with multidimensional cookies.

Which brings me to my 2nd question, assuming the answer to the first one doesn't help. I've got a multidimensional cookie that looks like the following:
code:
    someVariable =  HttpContext.Current.Request.Cookies["myCookies"]["data"];
I'm getting an error of "System.NullReferenceException: Object reference not set to an instance of an object." which seems to me that the "[data]" part of the cookie hasn't been initialized yet, thus just doesn't exist. Is there anyway in .Net to find this out so I can then set it?

I tried setting up a try catch similar to this:
code:
try
            {
                someVariable = HttpContext.Current.Request.Cookies["myCookies"]["data"];
            }
            catch 
            {
                HttpContext.Current.Request.Cookies["myCookies"]["data"] = "";
            }
but I get the same error in the catch.

Thanks!

This Post Sucks fucked around with this message at 23:36 on Mar 7, 2012

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

This Post Sucks posted:



code:
try
            {
                someVariable = HttpContext.Current.Request.Cookies["myCookies"]["data"];
            }
            catch 
            {
                HttpContext.Current.Request.Cookies["myCookies"]["data"] = "";
            }
but I get the same error in the catch.

Thanks!

Check if it's null. Don't rely on exceptions for normal flow of your application; exceptions indicate that something really bad happened.

This Post Sucks
Dec 27, 2004

It Gave Me Splinters!

Ithaqua posted:

Check if it's null. Don't rely on exceptions for normal flow of your application; exceptions indicate that something really bad happened.
Yeah, I usually don't. This was just the final attempt in a step of stuff. I should have stated that, the first thing I tried was:
code:
    if(HttpContext.Current.Request.Cookies["myCookies"]["data"] == null)
     {
        //Some Code
     }
and the same error resulted.

Zhentar
Sep 28, 2003

Brilliant Master Genius

This Post Sucks posted:

With the error of: "CS0103: The name 'Request' does not exist in the current context". From everything I've seen, Request should be in System.Web, right?

a) It's in System.Web.HttpContext
b) It's not static. You have to call it from an actual HttpContext object.

This Post Sucks posted:

code:
    someVariable =  HttpContext.Current.Request.Cookies["myCookies"]["data"];
I'm getting an error of "System.NullReferenceException: Object reference not set to an instance of an object." which seems to me that the "[data]" part of the cookie hasn't been initialized yet, thus just doesn't exist. Is there anyway in .Net to find this out so I can then set it?

Even if accessing an uninitialized item weren't allowed (it is), it wouldn't throw a NullReferenceException. As MSDN says, it is thrown when you dereference a null object. Presumably Cookies["myCookies"] is returning null.

This Post Sucks
Dec 27, 2004

It Gave Me Splinters!

Zhentar posted:

a) It's in System.Web.HttpContext
b) It's not static. You have to call it from an actual HttpContext object.
Ok, thanks!

quote:


Even if accessing an uninitialized item weren't allowed (it is), it wouldn't throw a NullReferenceException. As MSDN says, it is thrown when you dereference a null object. Presumably Cookies["myCookies"] is returning null.
I swear I checked for this at one point...:blush: Thanks.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

This Post Sucks posted:

Ok, thanks!

I swear I checked for this at one point...:blush: Thanks.

You need to download ReSharper. It'll make your life so much easier.

epswing
Nov 4, 2003

Soiled Meat
We're going to be selling a piece of software that stores data in (gasp) a database. The software is written in C#, and the database is SQL Server 2008 R2. The database credentials are currently sitting in a string somewhere in C#. "Installing" our product involves our technician(s) going on site, setting up the database and installing the software (not necessarily on the same machine), the point being that our clients have physical access to the machine(s) running the software and the database.

From what I understand, given physical access, I can assume that a determined client, with some effort, will be able to directly access the db, and I understand that I cannot truly prevent this. Our clients are, in general, not technically savvy. What I'd like is to make it "reasonably hard" to access the database directly, in the sense that my company can shrug and say "well, if they gained access the db directly, then they did so deliberately".

What can I do that's better than storing db credentials in a string, in the compiled software.

epswing fucked around with this message at 05:26 on Mar 8, 2012

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

epswing posted:

We're going to be selling a piece of software that stores data in (gasp) a database. The software is written in C#, and the database is SQL Server 2008 R2. The database credentials are currently sitting in a string somewhere in C#. "Installing" our product involves our technician(s) going on site, setting up the database and installing the software (not necessarily on the same machine), the point being that our clients have physical access to the machine(s) running the software and the database.

From what I understand, given physical access, I can assume that a determined client, with some effort, will be able to directly access the db, and I understand that I cannot truly prevent this. Our clients are, in general, not technically savvy. What I'd like is to make it "reasonably hard" to access the database directly, in the sense that my company can shrug and say "well, if they gained access the db directly, then they did so deliberately".

What can I do that's better than storing db credentials in a string, in the compiled software.

Someone with an administrative account is still going to be able to access the database. I wouldn't even classify that as "with some effort," it's just a fact of life.

If someone goes into your database and starts loving with it, there's nothing you can do about it. It's pretty much common sense that you just don't do that. Team Foundation Server, for example, stores everything in a database, and it doesn't go through any great pains to keep you out.

I wouldn't hard-code database credentials in your application, either. It's going to end up being a pain in someone's rear end at some point. Just use integrated security and be done with it.

boo_radley
Dec 30, 2005

Politeness costs nothing

epswing posted:

What can I do that's better than storing db credentials in a string, in the compiled software.

Writing a strong contract that charges your customers for breaking the antique store rules and breaking the database. Don't approach it as a technical issue, but a social one.

aBagorn
Aug 26, 2004
Ok, was talking to a Java programmer, and referenced the project I just did

View: http://pastebin.com/v8FkvK6r
Logic: http://pastebin.com/Mi5PCnvk

and he had some questions that I didn't have the answer to, and I was wondering if you guys do.

myfacebookJavafriend posted:

so anyway, does it make sense to write queries that are that similar over and over again for each of the 3 or 4 or 5 pieces of data that you want, or can you query multiple pieces of data and then just cache them in some struct and then just pull them from the struct?

it would potentially improve performance

and (although not as much of an issue for something that doesn't change often, like a list of network connections) keep the data from getting out of sync. what if the underlying data changes while the form is populating? say, between pulling the IP address and the gateway address, a new network connection opens up? you'll have more gateway addresses than IP addresses

fankey
Aug 31, 2001

I'm trying to port some code to the Async CTP with VS 2010. The code takes a list of ip address, sends a UDP packet to each address and returns the first address that responds. If no one responds within 5 seconds return null.

I've wrapped the UDP send a receive to use Tasks
code:
    static Task<int> SendAsync(this UdpClient client, byte[] buffer, IPEndPoint endPoint)
    {
      if( client == null ) throw new ArgumentNullException("client");
      return Task<int>.Factory.FromAsync(client.BeginSend, client.EndSend,
        buffer, buffer.Length, endPoint, null);
    }

    public static Task<byte[]> ReceiveAsync(this UdpClient client)
    {
      if (client == null) throw new ArgumentNullException("client");
      var tcs = new TaskCompletionSource<byte[]>(client);
      client.BeginReceive(iar =>
      {
        var t = (TaskCompletionSource<string>)iar.AsyncState;
        var s = (UdpClient)t.Task.AsyncState;
        try 
        {
          var ip = new IPEndPoint(IPAddress.Any, 0);
          s.EndReceive(iar, ref ip);
          t.SetResult(ip.Address.ToString()); 
        }
        catch (Exception exc) { t.SetException(exc); }
      }, tcs);
      return tcs.Task;
    }

    static Task<string> CheckIpAsyncInternal(string ip)
    {
      var tcs = new TaskCompletionSource<string>();
      UdpClient client = new UdpClient(0);
      IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), UdpPort);
      client.SendAsync(UdpData, endPoint);
      client.ReceiveAsync();
      tcs.TrySetResult(ip);
      return tcs.Task;
    }
What's not clear to me is the best way to accomplish iteration through my list of ips and return the result. The Task-based Asynchronous Pattern document talks about using Task.WhenAny() but that doesn't appear to exist in 2010 - I'm guessing that document is referencing 2012.

If I could use WhenAny() I assume I would so something like this
code:
    static Task<string> GetBestIpAsyncInternal(IEnumerable<string> ips)
    {
      var tcs = new TaskCompletionSource<string>();
      var tests = new List<Task<string>>();
      new Timer(self =>
      {
        tcs.TrySetResult(null);
      }).Change(500, -1);
      foreach (var ip in ips)
      {
        tests.Add(CheckIpAsyncInternal(ip));
      }
      tcs.TrySetResult(Task.WhenAny(tests).Result);
      return tcs.Task;
    }
but I'm not sure if that would work or not - and it doesn't really matter since WhenAny isn't available.

ljw1004
Jan 18, 2005

rum

fankey posted:

I'm trying to port some code to the Async CTP with VS 2010.

(1) In the AsyncCTP the function is called TaskEx.WhenAny. That's because the CTP didn't modify any of the framework types and so was unable to add an extension method on Task. But as for .NET45 it's called Task.WhenAny like it should be. I guess you're reading the document which we updated for .NET45.

(2) I notice that .NET45 has UdpClient.SendAsync and UdpClient.ReceiveAsync built in, so with .NET45 you won't need to define your own extension methods. NB. that SendAsync takes an additional parameter for length.

(3) Your code for CheckIpAsyncInternal looks odd. You're invoking "client.SendAsync" and "client.ReceiveAsync" in a fire-and-forget way, i.e. initiating the calls but not actually awaiting for it to finish. Also you were constructing the returned Task manually rather than just leaving it to the async keyword. I think it should have been something like

code:
static async Task<string> CheckIpAsyncInternal(string ip)
{
  UdpClient client = new UdpClient(0);
  IPEndPoint endPoint = ...
  await client.SendAsync(...);
  await client.ReceiveAsync(...);
  return ip;
}
(4) Here's how you might use Task.WhenAny (or TaskEx.WhenAny in the CTP):

code:
IEnumerable<string> ips = new[] { "1.2.3.4", "1.2.3.3", "1.2.3.5" };
IEnumerable<Task<string>> requests = from ip in ips select CheckIpAsyncInternal(ip);
Task<string> winner = await Task.WhenAny(requests);
string winning_ip = await winner;
(5) It might be nice to add cancellation. I don't actually know how UdpClient works with cancellation (and it doesn't accept a CancellationToken). Here's a random untried guess without even reading the docs for UdpClient...

code:
var cts = new CancellationTokenSource();
IEnumerable<string> ips = new[] { "1.2.3.4", "1.2.3.3", "1.2.3.5" };
IEnumerable<Task<string>> requests = from ip in ips select CheckIpAsyncInternal(ip, cts.Token);
Task<string> winner = await Task.WhenAny(requests);
cts.Cancel(); // to cancel any laggards
string winning_ip = await winner;

static async Task<string> CheckIpAsyncInternal(string ip, CancellationToken cancel)
{
    UdpClient client = new UdpClient(0);
    cancel.Register(delegate { client.Close(); });
    IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), UdpPort);
    await client.SendAsync(UdpData, UdpData.Length, endPoint);
    await client.ReceiveAsync();
    return ip;
}
*BUT* I don't know the cancellation story for UdpClient. I don't know if you're allowed to Close it mid-flight, and I don't know if doing this will cause SendAsync/ReceiveAsync to fail fast and throw exceptions, and I don't know if they're the exception you'd expect (i.e. inheriting from OperationCancelledException)

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

aBagorn posted:

Ok, was talking to a Java programmer, and referenced the project I just did

View: http://pastebin.com/v8FkvK6r
Logic: http://pastebin.com/Mi5PCnvk

and he had some questions that I didn't have the answer to, and I was wondering if you guys do.

What he's saying is reasonable. You could just keep a static List<NetworkInterface> and have logic to refresh it as appropriate.

(untested)
code:
        public static List<NetworkInterface> NetworkInterfaces { get; set; }
        static IpConfigLogic()
        {
            RefreshNetworkInterfaces();
        }
        public static void RefreshNetworkInterfaces()
        {
            NetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces().ToList();
        }
Then change your methods like this:
code:
        public List<string> ShowNetworkInterfaces()
        {
            var adapterText =
                (
                    from nic in NetworkInterfaces
                    where nic.OperationalStatus == OperationalStatus.Up
                    select nic.Description
                );
            return adapterText.ToList();
        }

fankey
Aug 31, 2001

ljw1004 posted:

(3) Your code for CheckIpAsyncInternal looks odd. You're invoking "client.SendAsync" and "client.ReceiveAsync" in a fire-and-forget way, i.e. initiating the calls but not actually awaiting for it to finish. Also you were constructing the returned Task manually rather than just leaving it to the async keyword. I think it should have been something like
That makes sense. I think I'm still a little confused as to when you need to use the await keyword.

ljw1004 posted:

(5) It might be nice to add cancellation. I don't actually know how UdpClient works with cancellation (and it doesn't accept a CancellationToken). Here's a random untried guess without even reading the docs for UdpClient...
I'll try the cancellation. Do the items that are left in the WhenAny call get cancelled automatically. Would there be an easy way to cancel everything after a given period of time?

Thanks for all the useful info.

ljw1004
Jan 18, 2005

rum

fankey posted:

That makes sense. I think I'm still a little confused as to when you need to use the await keyword.

Answer: use the "await" operator when you want to suspend the logical flow of execution within this method until the thing has finished. In this case you probably don't want to receive until after the thing's been sent, and you certainly don't want to return until after the thing's been received.

fankey posted:

I'll try the cancellation. Do the items that are left in the WhenAny call get cancelled automatically. Would there be an easy way to cancel everything after a given period of time?

No the things left in WhenAny do not get cancelled automatically. There's really no automatic cancellation anywhere. That's why you have to build it yourself like above.

An easy way to cancel stuff after a given period of time: "cts.TimeoutAfter(...)".

Adbot
ADBOT LOVES YOU

Nurbs
Aug 31, 2001

Three fries short of a happy meal...Whacko!
I'm working with a Soap service via a class implementing SoapHttpWebClientProtocol generated by wsdl.exe. What I'd like to do is specify a few of my own types to use with this class, but don't want to have to decorate it with an XmlInclude attribute for each class.

From my understanding, the constructor for XmlSerializer would allow me to specify 'known' types at runtime, but I have no idea of if / how I can inject this so that my XmlSerializer is used instead of whatever.

Anyone have a good thought or solution?

  • Locked thread