Category Archives: Asp.Net

Extract Connection Strings to an external file from web.config

I found this on StackOverflow, so I posted a link to it here for my own future reference.

You can abstract (or extract) the Connection Strings for your Asp.Net out of Web.Config and keep them in a separate file. This is helpful if each developer needs their own connection strings defined. You would *not* want to include this file in the tracked files of your repo, or else each developer’s file would get updated with any changes.

http://stackoverflow.com/questions/6582970/separate-connectionstrings-and-mailsettings-from-web-config-possible

Here’s how it works:

image

Here’s a link to the MSDN document explaining it in greater detail:

 http://msdn.microsoft.com/en-us/library/ms254494%28v=vs.110%29.aspx

Quick Peek at Visual Studio LightSwitch

I’ve been curious about Visual Studio LightSwitch for a while. It’s a rapid application development tool from Microsoft which lets you quickly develop HTML/Javascript CRUD apps and small business apps for web browsers and mobile devices (I think it can do desktop apps too, but it uses Silverlight to do it, and I’m only interested in web apps these days.)  LightSwitch is installed out-of the box in Visual Studio 2013 Professional and the new (free) Visual Studio Community 2013 edition.

Note: This is not a deep-dive into LightSwitch. It’s just a quick 5 minute review of what I accomplished in less than 30 minutes piddling around with this thing one evening to get a peek at what it’s like. Before I got started, I had watched this nice video on YouTube and it really helped me jump right in: http://youtu.be/tu5G8AsOlr0

I recall hearing at one point, when LightSwitch first came out, that some people proposed it as an alternative to Visual FoxPro, or at least a path forward for FoxPro devs who had never built web apps before or did not want to take the full plunge into the .Net world.  So, I’m curious if any of my FoxPro peeps have taken up with this? If so, let’s hear from you.

Here we go… Basically, I found it dirt simple to get up and running. I just created a new LighSwitch prject in Visual Studio and pointed it to a database in Sql Server Express running on my local developer machine (I already had Sql Server Express installed for other .Net work). Next I picked which tables I wanted to work with in the app. You then add views for any given table, selecting which fields to show.  The initial page layouts are auto-generated for the selected fields, and you’ll quickly have a live list view and edit page running in your browser.

I’ve built real web apps in Ruby on Rails and Asp.Net MVC with Entity Framework, and I’ll tell you hands down from real experience that getting a simple CRUD page alive in LightSwitch is much  easier than in either of these other two platforms. Now, I’m betting there are some real limitations that come with using a simple application framework like LightSwitch. So, I don’t dare suggest that an app built in LightSwicth can compete with all the features needed to build a complex business app. You’ll have to learn more about that for yourself. However, there are lots of examples and forums where you can learn how to include advanced UI or backend code when needed.

Here’s a simple edit page. Just make a change and click the little Save icon in the upper right corner of the screen:

image

To create or edit the views, you use a treeview designer-like UI in Visual Studio to create rows, columns, groups, fields, as well as a command bar for action buttons and other UI controls. It adds default label captions above each field, but you can override those as well as field widths and other styling options in the Properties window (see blow).

image

Here is a view of the simple Property Editor showing the various properties you can tweak for each control on the page layout.

image

 

Ok, it’s all up to you from here. Watch the video linked above, and try it out for yourself.

Next Step

The next three things I plan to explore:

  1. How it handles lookups, like when you need a dropdown list to choose a value from a lookup table and store the ID in a local field. http://blogs.msdn.com/b/bethmassi/archive/2012/01/12/creating-cascading-drop-down-lists-in-visual-studio-lightswitch.aspx
  2. Client side, or backend validation.
  3. Showing related child records in a grid on the same page as the parent detail fields.

If my interest is there, and my time allows, I’ll update this page if I accomplish anything with these items above.

Resources

LightSwitch on MSDN: http://msdn.microsoft.com/en-us/vstudio/lightswitch.aspx (lots of how-to-get-started content.)

MSDN Forum for LightSwitch: https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=lightswitch

PluralSight courses on LightSwitch: http://www.pluralsight.com/courses/visual-studio-lightswitch2012

Free video: http://youtu.be/tu5G8AsOlr0

LightSwitch articles on CODE Magazine website: http://www.codemag.com/Magazine/ByCategory/Lightswitch

SSMS – Generate Scripts – Data only – Cyclic dependencies found error

When trying to generate data only scripts from a Sql Server 2012 database, I was getting this error from Sql Server Management Studio 2012:

Microsoft.SqlServer.Management.SqlScriptPublish.SqlScriptPublishException: An error occurred while scripting the objects. —> Microsoft.SqlServer.Management.Smo.SmoException: Cyclic dependencies found. at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.DependencyGraphTraversal(Int32 num, Dictionary2 dictionary, List1 sortedList, HashSet1 visited, HashSet1 current) at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.DependencyGraphTraversal(Int32 num, Dictionary2 dictionary, List1 sortedList, HashSet1 visited, HashSet1 current) at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.DependencyGraphTraversal(Int32 num, Dictionary2 dictionary, List1 sortedList, HashSet1 visited, HashSet1 current) at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.DependencyGraphTraversal(Int32 num, Dictionary2 dictionary, List1 sortedList, HashSet1 visited, HashSet1 current) at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.DependencyGraphTraversal(Int32 num, Dictionary2 dictionary, List1 sortedList, HashSet1 visited, HashSet1 current) at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.SortDictionary(Dictionary2 dictionary) at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.SortDataSet(DataSet ds) at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.SortDataSet(List1 objectList, Dictionary2 idDictionary, DataSet ds) at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.ExecuteQueryUsingTempTable(List1 objectList, List1 list, String query) at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.ResolveTableOnlyDependencies() at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.ResolveDependencies() at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.Order(IEnumerable1 urns) at Microsoft.SqlServer.Management.Smo.ScriptMaker.DiscoverOrderScript(IEnumerable1 urns) at Microsoft.SqlServer.Management.Smo.ScriptMaker.ScriptWorker(List1 urns, ISmoScriptWriter writer) at Microsoft.SqlServer.Management.Smo.ScriptMaker.Script(Urn[] urns, ISmoScriptWriter writer) at Microsoft.SqlServer.Management.SqlScriptPublish.SqlScriptGenerator.DoScript(ScriptOutputOptions outputOptions) — End of inner exception stack trace — at Microsoft.SqlServer.Management.SqlScriptPublish.GeneratePublishPage.worker_DoWork(Object sender, DoWorkEventArgs e) at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e) at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)

 

This database was originally on Sql Server 2008, and I could script it without any problems at that time, which I did many times. Then, about a month ago, we moved it to Sql Server 2012, and when I tried to script the database again, using Sql Server Management 2012, I got this error.

I googled around and found this helpful script to find the offending circular references ( http://blogs.msdn.com/b/sqlazure/archive/2010/07/01/10033575.aspx )  (Update-  new link:  http://i1.blogs.msdn.com/b/appfabricannounce/archive/2010/07/01/finding-circular-foreign-key-references.aspx ) which I ran in a query window to see what was wrong. Sure enough, it showed me the circular references and the results were spot on, but I wanted to keep the references in place. Everything worked fine when accessed from Entity Framework, and I was afraid to mess with the relations.   (In fact, the database was created in Sql Server 2012 by the Entity Framework using the update-database command. So, all the relations, foreign keys, indexes, etc came originally from the class definitions in EF.)

Problem Solved!

Then, on a whim, knowing that I had successfully scripted this database before, I connected to the Sql Server 2012 instance using Sql Server Management 2008 R2, and I was able to generated the scripts without error!!

Note, that I did data-only, and I had to allow it to script all database objects. I tried to select only certain tables, but that gave some other errors that I wasn’t willing to track down, so I just did the whole thing.

 

So, good luck to you… I hope this will help the next person who faces this problem.

Detecting Session Timeout in Asp.Net

I recently had the need in my Asp.Net Webforms application to determine if a Session Timeout had occurred while the user was logged in to the app. As you know, while working in a Line Of Business app, many users can be drawn away from the app for extended periods of time after logging in. Upon returning to the app and making their next postback (by clicking some link or button on the form), most applications will have a mechanism to check the timeout limit set in Web.config and force the user to login again if the timeout limit has been passed. This is a basic security mechanism that is broadly used in web apps, and I wanted this behavior in my application.

Well, it turns out there is no built-in event or flag in the .Net framework that indicates when a Session Timeout has occurred. As I began what I thought would be a routine Google search, I found various solutions offered up by many developers who I’m sure are much smarter than me. After filtering through all the variations and approaches I saw on the web, I have trimmed it down to a simple method that works well for me, so I wanted to offer it up here to help anyone else who may encounter this need. You can add this method to your base form or master page code behind.

This simple method will return true if a Session Timeout has occurred, or false if not. You can call this method and take the desired action if true is returned. In my case, I log the user out and redirect them to the login page, passing a querystring parameter that triggers my login page to notify the user what has happened.

Method CheckForSessionTimout():

public bool CheckForSessionTimeout()
{
  if (Context.Session != null && Context.Session.IsNewSession)
  {
    string cookieHeader = Page.Request.Headers["Cookie"];
    if ((null != cookieHeader) && (cookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
     return true;
    else
     return false;
   }
   else
    return false;
}

Here is how I call the above method from the OnInit() method of my MasterPage:

if (CheckForSessionTimeout())
{
 if (Page.Request.IsAuthenticated)
 {
   FormsAuthentication.SignOut();
 }
 NavigateToLoginPage(true);
}

And here is the code for my NavigateToLoginPage() method, where the parameter true means “alert the user that a timeout has occurred” :

public void NavigateToLoginPage(bool TimeOutHasOccurred)
{
  Response.Redirect("~/Login.aspx?mode=timeout");
}

image

On the Login.aspx page, I look for the QueryString parameter of “mode” with a value of “timeout” and display this beautiful yellow <div> to tell the user what has happened.