Posts

Showing posts from February, 2009

Exchange/Outlook integration, Time Zones and conversions

Generic code to create all tasks at 0000 at the app server time zone Wherever the app is installed, it will use that Time Zone – IST, EST etc private static void setMeetingTimeZone(CalendarItemType result) { // from http://msdn.microsoft.com/en-us/library/bb738399.aspx result.MeetingTimeZone = new TimeZoneType(); result.MeetingTimeZone.TimeZoneName = TimeZoneInfo.Local.StandardName; } private void saveOccurences(int recurringMasterTaskId, List occurences) { foreach (CalendarItemType occurence in occurences) { TaskDALC.InsertTaskOccurence(recurringMasterTaskId, TimeZoneInfo.ConvertTimeFromUtc(occurence.Start, TimeZoneInfo.Local), TimeZoneInfo.ConvertTimeFromUtc(occurence.End, TimeZoneInfo.Local), occurence.ItemId.Id, occurence.ItemId.ChangeKey, "", ""); } } Outlook client could be anywhere and can send a date not in sync with Exchange. So instead of Item.Start we send the date as Item.StartUTC in the script (plus there was a client culture related fix too). Month(It

Inport 2009 Note

The 60+ posts showing a date of Feb 25 2009 were all imported here from a much older blog, but the dates were lost during the import process.

Outlook - attachment warnings and folder cleanups

'Press Alt-F11 and enter this first one in "ThisOutlookSession" to warn you whenever you write the word "attach" and forget to send an attachment 'If it doesn't work, reduce macro security to "medium" and restart Outlook Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean) Dim lngres As Long If InStr(1, UCase(Item.Body), "ATTACH") <> 0 Then If Item.Attachments.Count = 0 Then lngres = MsgBox("No attachment - send anyway?", _ vbYesNo + vbDefaultButton2 + vbQuestion, "No attachment") If lngres = vbNo Then Cancel = True End If End If End Sub 'This second one is trickier but more useful. It converts all mails in a folder to plain text and removes attachments. You have to add a rule to use it 'Enter this one in "ThisOutlookSession" too but add a rule to run when mails arrive and set it to run this script 'DO N

TFS issues raised and replies from MS

Q. Why does TFS Build require the 3.5 SDK even if it is building a 2.0 solution? Ans. Team Build uses MSBUILD in the background. When you installed Team Build 2008 it installs the 3.5 framework so when you run a build it using the 3.5 version of MSBUILD. This is hardcoded and cannot be changed. Q. A build server does not seem to be able to handle multiple builds on the same server since it causes workspaces to clash. It happens if you're trying to do 2 different builds on the same folders. It says one folder cannot belong to 2 workspaces. Is this because TFS uses file paths as absolute references to source safe paths once the workspace is created? Is there a workaround? Ans. Typically you queue your builds and the builds run one at a time sequentially so using the same workspace would never be a problem. You can run multiple build agents on the same computer, but doing so could cause problems like what you are seeing. When we do a build we lock down the build folder while doing th

DB, UI and MSI builds with TFS

I just finished an app called “C:\XYZ\Content Center\Database\ABC_Dev\DbBuilder” It’s a simple app that parses through a set of Build items (sql or project files) and builds them against a DB. The Build items, DB details and a few other things are configurable. For ex, for a normal / daily build: <add key="BuildItems" value="Scripts\ABC50_ChangeScript.sql,Scripts\ABC52_ChangeScript.sql,Scrip ts\ApABConfig.sql,Scripts\DeleteOnlyCode.sql,Views\Views.ssmssqlproj,Triggers\Triggers.ssm ssqlproj, Procedures\Procedures.ssmssqlproj,Functions\Functions.ssmssqlproj"/> (I’ve also fixed DeleteOnlyCode.sql above and included dropping views) More importantly, I’ve finished integrating it with the TFS build system (which took longer than the actual application). So we can fully automate our DB build now. I’ve still not included it though since right now our DB build will fail. Please let me know if we should fix the DB errors first or if I should go ahead and include it anyw

TFS multiple builds and build numbering

There were two problems in making a new automated build. 1. TFS requires a new build agent for every team project That means either installing 2 build services on Periyar or having a new build machine (Are we getting any value add out of having a separate team project for every branch?) 2. The same folder cannot be used as the workspace for more than one source control folder C:\XYZ can be used only for any one build The workarounds I did were 1. I am defining both the builds in the XYZProduct2 team project (I can point to any source control folder anyway) 2. There are now 3 virtual folders pointing to the same physical folder linkd C:\XYZ D:\Projects\Builds\Sources linkd D:\Projects\Builds\XYZProduct2 D:\Projects\Builds\Sources linkd D:\Projects\Builds\XYZProduct5.1.0.10 D:\Projects\Builds\Sources For every new build, we can make a new virtual folder and point it to D:\Projects\Builds\Sources C:\XYZ will always point to this folder anyway. So all builds happen in one folder with the s

Linkd

We are moving to a new folder structure where we will be using a virtual folder (specifically an “NTFS junction point”) called C:\XYZ instead of the old subst R: drive. The subst R: drive implementation had a lot of issues like no integration with IIS, VSTS2008, TFS Build etc Steps to change: 1. Please remove your existing R: drive “subst r: /D” 2. Remove any .bat file you have for creating the r: drive on startup 3. Install the Windows Server 2003 Resource Kit (even on XP) http://www.microsoft.com/downloads/details.aspx?FamilyID=9d467a69-57ff-4 ae7-96ee-b18c4790cffd&displaylang=en 4. Create the symbolic link (one time only, no bat file required) “linkd C:\XYZ E:\Projects\XYZ” 5. Delete your existing workspace and create a new one with "C:\XYZ" instead of R: as the root folder of your team project.

Migration process followed

Install SQL Analyzer Install TFS Install Team Explorer [Thursday] Lock VSS DB Incremental copy Unlock VSS DB Install VSS2005 Installed TFS plug-in for ABC_Dev.ssmssln Cleaned up VSS copy Unbound local ABCWebComplete.sln and JobServiceComplete.sln and bound to new VSS copy Change 2008 plug-in from TFS to VSS Converted ABCWebComplete.sln and JobServiceComplete.sln to 2008 , built and checked in [on a R51 laptop] Analyze VSS copy - ANALYZE -f -d -v1 "D:\VssBackup\data" Deleted beta folders from VSS (missed during cleanup) VSSConverter Analyze "D:\VssBackup\VSS2TeamFoundation\settings.xml" VSSConverter Migrate "D:\VssBackup\VSS2TeamFoundation\ migration_settings.xml" Labelled TFS [Friday] Fixed R: Fixed ABC50 (checked Linkd, Mountvol etc) Further cleaned up TFS Tried branch and merge of sample project Discarded SQL studio (Tried manual checkouts, manual edits, another trial etc. Process/plugin is buggy and not repeatable)

Useful links I found on TFS and VSS to TFS Migration

http://blogs.microsoft.co.il/blogs/srlteam/archive/2006/09/26/3367.aspx VSS to Team System Migration - complete Checklist http://blogs.msdn.com/team_foundation/archive/2005/02/23/379179.aspx Complete overview of Branching, Merging, and Shelving http://www.woodwardweb.com/vsts/000291.html (about Shelvesets) http://blogs.msdn.com/buckh/archive/2005/06/03/425125.aspx (CVS compared with TFS, note the atomic checkins) http://msdn2.microsoft.com/en-us/library/w6y8ezzs(VS.80).aspx (Shelve Command)

distinct on DataTable

2.0 feature DataView.ToTable Method (String, Boolean, String[])

DeleteOnlyCode.sql - SQL Server 2005

declare @procName varchar(500) declare cur cursor for select [name] from sys.objects where type = ‘p’ AND (NAME LIKE ‘USP_%’ OR NAME LIKE ‘cv_%’ ) open cur fetch next from cur into @procName while @@fetch_status = 0 begin exec(‘drop procedure ‘ + @procName) fetch next from cur into @procName end close cur deallocate cur declare @procName varchar(500) declare cur cursor for select [name] from sys.objects where type = ‘tr’ AND (NAME LIKE ‘trg_%’ ) open cur fetch next from cur into @procName while @@fetch_status = 0 begin exec(‘drop trigger ‘ + @procName) fetch next from cur into @procName end close cur deallocate cur declare @procName varchar(500) declare cur cursor for select [name] from sys.objects where (type = ‘fn’ or type = ‘if’ or type = ‘tf’) AND (NAME LIKE ‘ufn_%’ ) open cur fetch next from cur into @procName while @@fetch_status = 0 begin exec(‘drop function ‘ + @procName) fetch next from cur into @procName end close cur deallocate cur • Couldn’t find a definite way of different

ensureSecurity

It was this little bool that was causing the web to not be able to talk to the Service RemotingConfiguration.Configure(string filename, bool ensureSecurity); http://msdn2.microsoft.com/en-us/library/system.runtime.remoting.remotingconfiguration.configure.aspx Apparently, the 1.1 version of this method didn’t have that 2nd parameter. Also, we should probably ensure security later and actually pass the required authorization details to the service instead of disabling security.

Migrating to 2.0 aspnet

http://msdn2.microsoft.com/en-us/library/1d3t3c61.aspx "Under ASP.NET V1.1 persistent cookies do not time out, regardless of the setting of the timeout attribute. However, as of ASP.NET V2.0, persistent cookies do time out according to the timeout attribute." This and the fact that all the page_load bindings will have to be removed are the most important changes when migrating from 1.1 to 2.0 aspnet. HtmlForm.DefaultButton Property - new 2.0 feature http://msdn2.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlform.defaultbutton.aspx

2.0 aspnet_compiler

aspnet_compiler -v /Nwd -p “C:\iughuih\Visual Studio 2005\WebSites\NorthwindWebSite” “C:\kjhjkh\Visual Studio 2005\WebSites\NorthwindWebDeploy” (Then webshare to view with IIS - set to 2.0 if default is 1.1)

2.0 profile anonymousIdentification

<profile defaultProvider="AspNetSqlProfileProvider"> <providers> <clear/> <add name="AspNetSqlProfileProvider" connectionStringName="aspnetdbConnectionString2" applicationName="/" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> </providers> <properties> <add name="Favorites" type="FavBook" allowAnonymous="true" serializeAs="Binary" /> </properties> </profile> <anonymousIdentification enabled="true"/> </system.web>

2.0 securityTrimmingEnabled

<siteMap> <providers> <clear /> <add siteMapFile=”web.sitemap” name=”AspNetXmlSiteMapProvider” type=”System.Web.XmlSiteMapProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” securityTrimmingEnabled=”true” /> </providers> </siteMap>

2.0 aspnetdb

aspnet_regsql <add name=”aspnetdbConnectionString” connectionString=”Data Source=10.140.4.107;Initial Catalog=aspnetdb;Integrated Security=True” providerName=”System.Data.SqlClient” /> (System.Configuration.ConfigurationManager.ConnectionStrings[”aspnetdbConnectionString”].ConnectionString) <membership> <providers> <add name=”AspNetSqlMembershipProvider” type=”System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” connectionStringName=”aspnetdbConnectionString” enablePasswordRetrieval=”false” enablePasswordReset=”true” requiresQuestionAndAnswer=”true” applicationName=”/” requiresUniqueEmail=”false” passwordFormat=”Hashed” maxInvalidPasswordAttempts=”5” minRequiredPasswordLength=”7” minRequiredNonalphanumericCharacters=”1” passwordAttemptWindow=”10” passwordStrengthRegularExpression=”” /> </providers> </membership> <roleManager> <providers> <add name=”AspNetSqlRoleProvid

2.0 Enabling the database for SQL cache dependency (With windows auth)

C:\Program Files\Microsoft Visual Studio 8\VC>aspnet_regsql -S 10.140.4.107 -E -d Northwind -ed -t Customers -et <caching> <sqlCacheDependency enabled=”true” pollTime=”600”> <databases> <add name=”Northwind” connectionStringName=”NorthwindConnectionString”/> </databases> </sqlCacheDependency> </caching> </system.web> </configuration> <asp:SqlDataSource ID=”SqlDataSource1” runat=”server” CacheDuration=”120” ConnectionString=”<%$ ConnectionStrings:NorthwindConnectionString %>” EnableCaching=”True” SelectCommand=”SELECT * FROM [Customers]” SqlCacheDependency=”Northwind:Customers”></asp:SqlDataSource>

"Why use STATIC keyword with the main method"

“What will happen if the class doesn’t have a public constructor ?”

override vs new

1. override calls method of object new calls method of variable 2. “cannot override inherited member because it is not marked virtual, abstract, or override” new does not require “virtual, abstract, or override”

The Obsolete attribute

I was going to recommend using the Obsolete attribute for DefType.Refresh() We could even have done a [Obsolete(“Refresh not allowed for def types”, true)] so that the compiler issues an error and prints out a message. However, it won’t work since this particular case is a virtual/override method. ‘Obsolete’ is ignored for an overridden method. However, it should be useful in other cases. Just FYI

BindingFlags.Static | BindingFlags.Instance

The reason we were not able to access the private FieldInfo with NonPublic was that you have to specify if it is a Static field or not (an ‘Instance’ field) This combination will ensure that you get your field no matter what - BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance Console.WriteLine(T.GetField(“a”, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance).GetValue(x));

Disable zipped compressed folder support

http://www.tacktech.com/display.cfm?ttid=259 Solution: Click Start > Run... Type regsvr32 /u %windir%\system32\zipfldr.dll Click the OK button. To re-enable: Click Start > Run... Type regsvr32 %windir%\system32\zipfldr.dll Click the OK button.

Finding duplicate rows without a primary key

select a.CATEGORY_ID, a.CATEGORY_CD, a.TREE_NODE_NUM, a.PARENT_NODE_NAME from (select PARENT_NODE_NAME, TREE_NODE_NUM, CATEGORY_ID, CATEGORY_CD, rownum as num from ps_z_CAT_Tree_vw) a, (select PARENT_NODE_NAME, TREE_NODE_NUM, CATEGORY_ID, CATEGORY_CD, rownum as num from ps_z_CAT_Tree_vw) b where a.CATEGORY_ID = b.CATEGORY_ID and a.num<>b.num There’s no need to list both sets of fields because the union will cause both sets to be shown in different rows anyway.

Nhibernate session deserialized in another APP Domain

We have fixed the null key exception by adding this item in theÿ nhiberSQLServerSettings.config <add key=”hibernate.session_factory_name” value=”xxx_NHibernate_SQL_SessionFactory”/> The reason was when nhibernate session was deserialized in another APP Domain (another server), it was looking for the sameÿsession factory by the name. Earlier we were not setting this name property so a randomly generated GUID was assigned as the sessionÿfactoryÿname. Implications were that the name of the session factory was different in different app domains in different server. Hence session couldn’t find its factory and so couldn’t deserialize itself. Resolution is just to add this property in the config file.

SecurityException mscorlib.dll

As you know I changed my PC recently and on trying to run our nant scripts, I got this error “An unhandled exception of type ‘System.Security.SecurityException’ occurred in mscorlib.dll” And neither http://support.microsoft.com/kb/836989 (I already had SP1 and reinstalling didn’t help) Nor http://p2p.wrox.com/topic.asp?TOPIC_ID=3077 on that search worked for me. What finally worked was Control Panel Administrative Tools Microsoft .NET Framework 1.1 Wizards Adjust .Net security -> this comp -> local intranet=full trust

Run time primary keys for Datagrids

I believe a common problem we have faced in many of our screens is not having a primary key for the items in the datagrid. It sometimes becomes very difficult to differentiate between rows of the grids, especially in javascript and we have to use field combinations. Sometimes even that won’t work (if all fields are equal in two rows). Here’s an easy work around. What this does is generate an integral key for every row. You can use either the property that just-returns the key or increments-and-returns the key depending on whether you’re on the same row or moving to the next row. <asp:TemplateColumn HeaderText=”Authorized”> <ItemTemplate> <input type=”text” name=”Txt<%#IncLogSn%>” value=”<%#DataBinder.Eval(Container.DataItem,”Authorized”)%>”> <input type=”hidden” name=”Hid<%#LastLogSn%>” value=”<%#DataBinder.Eval(Container.DataItem,”Authorized”)%>”> </asp:TextBox> </ItemTemplate> </asp:TemplateColumn> private int LogSeria

Modifying datagrids without using DataGrid_ItemDataBound

A common requirement in most of our screens An advantage in the second case is that because you’re using a .Net literal control, the cell will maintain its value across post-backs You can code to specific conditions by varying the implementation of returnComparisonBool() <!-- For an image --> <asp:TemplateColumn HeaderText=”Physical Location” ItemStyle-HorizontalAlign=”Center” ItemStyle-VerticalAlign=”Middle”> <ItemTemplate> <a href=”#” onclick=’return launchAddrs(<%#DataBinder.Eval(Container.DataItem,”alt_id”)%>);’> <asp:Image ID=”Image1” Runat=”server” Visible=’<%#returnComparisonBool(DataBinder.Eval(Container.DataItem,”PHYS_LOC_CD”), “ALT”)%>’ ImageUrl=”../Images/VIEWB.bmp”> </asp:Image></a> </ItemTemplate> </asp:TemplateColumn> <!-- For an simple string --> <asp:TemplateColumn HeaderText=”Issued?” ItemStyle-HorizontalAlign=”Center” ItemStyle-VerticalAlign=”Middle”> <ItemTemplate> <asp:Literal Run

CacheItemPriority.NotRemovable

CacheItemPriority.NotRemovable - doesn’t make much difference -- Also, I found something that maybe useful “You can indirectly control the memory size of the cache by using the memoryLimit attribute in in machine.config. The cache engine will start throwing items out of the cache agressively when that memory limit is getting close.” I’ll try reducing that and testing on my PC Also, see this Apparently, things can get thrown out even if “NotRemovable” Which is strange because apparently even “inProc session” uses NotRemovable cache internally Another thing is We’re using DateTime.MaxValue for absoluteExpiration ideally, we should use NoAbsoluteExpiration But internally they are the same But I’ll try reducing the memory and see Cache.NoAbsoluteExpiration “When used, this field sets the absoluteExpiration parameter equal to MaxValue, which is a constant representing “ Same thing, actually... We do this Cache.Insert(index, _CacheKeys, null, DateTime.MaxValue, Ideally, it should be Cache.

Response.Redirect or End

We have a new issue as a result of moving the NHiberSession to HttpSessionState. In short, whenever a Response.Redirect or a Response.End is called, the Global_ReleaseRequestState is bypassed. Instead, a ThreadAbortException is raised (as you may know) and then Application_EndRequest is raised directly. This is normal. In our case though, before Application_EndRequest, a SerializationException exception is raised because our NHiberSession is still connected. NHiberSession cannot be serialized when connected and it can only be disconnected in Global_ReleaseRequestState since we need the session for it. I tried to store the NHiberSession (a similar sample object) in System.Web.HttpRuntime.Cache and disconnect it in Application_EndRequest but as you can infer from the above, the Session has already been unsuccessfully serialized by then and this has no effect. Yes, specifying the second parameter as false solves the Response.Redirect problem. In fact, this is supposed to be the correct wa

Too many cookies?

”We’re setting too many cookies and so losing the session.” Number and size limits of a cookie in Internet Explorer At least 300 cookies At least 4096 bytes per cookie (as measured by the size of the characters that comprise the cookie non-terminal in the syntax description of the Set-Cookie header) At least 20 cookies per unique host or domain name (Also, see the limits for Netscape ) Basically, our application stored various little values in a cookie and when those values exceeded 20, the user got logged off.

C# constant arrays

As you must know, there’s no such thing as C# constant arrays - http://www.google.com/search?hl=en&q=c%23+const+array For example, the below code will not compile const int [] constIntArray = newint [] {2, 3, 4}; On the other hand, a static readonly will compile static readonly int [] constIntArray = new int[] {1, 2, 3}; But it’s of no use since even though cannot reassign the array itself, you can replace individual values. The readonly makes you think it cannot be changed, which is bad because you could end up wrong values at runtime. What I needed was an array that I couldn’t re-assign at run time. As usual, I was trying to avoid hard-coding something and in this case it was field names. I needed some way to work with field names so that even if the names or the order of the fields changed tomorrow, I could just change an enum and the constants and the rest of the code would work fine. Of course, I could simply do this public enum Fields { ItemId = 0, ShortDescription =

Great Calendar Popups

http://www.mattkruse.com/javascript/calendarpopup/

.Net processes and AppDomains

Following-up on the queries regarding Assemblies and compilation that day, if you can find out whether .Net PEs run in separate processes or the same process, do let me know. I’ve been looking around but haven’t found anything. There’s plenty of stuff about ASP.Net but nothing about winforms, console apps or PEs in general. [I just tried this] A simple Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().Id); In two different console apps (or even two instances of the same app) gives different values whereas a Response.Write(System.Diagnostics.Process.GetCurrentProcess().Id); For two different webapps gives the same value (as expected). But I wouldn’t consider this finding conclusive. Also, checkout this great link on AppDomains http://www.odetocode.com/Articles/305.aspx

Must- Have Utilities

I came across this useful site a while back.

Virtual directory vs web sharing

The web sharing tab on the properties window of any given folder is a very quick and effective alternative to manually making a virtual directory of the same folder through inetmgr .

.Net debug or release

A description : - "See this http://weblogs.asp.net/jkey/archive/2003/11/23/39383.aspx His method is wrong, of course, but that should put you on the right track. The tricky part was not being able to unload the assemblies and not being able to read the assemblies without loading them into the App domain in .Net 1.1 I believe this problem has been solved in 2.0 (ReflectionOnlyLoad and ReflectionOnlyLoadFrom) Another link This is why I have to re-load the app whenever it reads the Dlls, to release the assemblies." The code for telling the difference : - foreach (FileInfo FileInfoEach in DiScripts.GetFiles("*.dll")) { OneAssembly = Assembly.LoadFile(FileInfoEach.FullName); Object[] CustomAttributes = OneAssembly.GetCustomAttributes(false); bool IsDebuggable = false; foreach (Object CustomAttributein CustomAttributes) { if (CustomAttribute is DebuggableAttribute) if(((DebuggableAttribute)CustomAttribute).IsJITTrackingEnabled ) { IsDebuggable = true; break; } } DtDlls.

Problem in Setup projects for .Net 1.1

“The problem was that for Setup projects, VS.Net does not change the source dlls locations when you toggle between ‘release’ and ‘debug’ before building. So if you initially configured your Setup project in debug mode, even if you build your Setup file in release mode, it picks up the debug versions of all the dependent dlls (but not the main assembly).” PS: The solution is to remake the setup project and/or refresh the dependencies so that they point to the “obj/release” folder.

Avoiding server trips

A lot of the controls like radio buttons and checkboxes (and the cancel buttons) need not be web controls at all. They simply make the assembly heavier and slower. Also, if they are html controls, there is less chance of people writing server-side code for them When assigning attributes (like ‘onClick’) to web controls in the page load, it needs to be done only when (!IsPostBack) For more up-to-date information, the following link seems to be a good reference, especially for IE. But please note that a lot of code that works on IE may not work on other browsers, so use this link only for IE based development. http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/dhtml_reference_entry.asp I completely agree with *** in that there really is no need to hit the server unless you need something from the DB. Nearly all the work done on the forms right now - enabling / disabling, selection / de-selection of checkboxes and rows on grids, launching Pop-Ups etc - can

The variable 'exception' is declared but never used

I also see a lot of these warnings catch(Exception ex) { return false; } (The variable ‘ex’ is declared but never used) Please remember that there is no need to declare the exception object if you aren’t going to use it. This same code can simply be written as catch { return false; } It saves memory and if no Exception type is specified in the catch block, System.Exception is assumed. Even if you need to throw it, the following code will work fine catch { throw; } If you need to catch some specific exception, you can still do it without declaring the object catch (ApplicationException) { throw; } Or catch (ApplicationException) { return false; } [Update] While writing catch { throw; } is as good as not writing anything, writing catch(Exception Ex) { throw Ex; } effectively clears out any existing StackTrace in Ex; probably not a good idea.

Persisting values in web applications

Another thing I would like to caution against is the use of global variables in the .cs files in web-forms - I just saw an example of this in EditLineItem.ascx (isSerialized) Please remember that unlike windows forms, web-forms do not stay in memory between events on the page (post backs). The object is disposed after every load / post-back (That’s why the page_load is called on every refresh / post-back) So if you store a value in a public variable in one event of the page, it will revert back to the default in the next. The viewstate is the ideal place to persist values between post-backs. The general thumb-rule for persisting values in web apps is Viewstate for storing values on a PAGE (will only be available for that one page for that one session) between post-backs Session for storing values across pages for one SESSION Application for storing values across the application lifetime (between IIS-resets, the value will be available to all sessions and in all pages)

Avoiding accessing DataGridItem.Cells[] - some old tricks

Some (working) sample code on how you can make your code safe from changes to the columns in a Datagrid and avoid accessing DataGridItem.cells[] Specify a DataKeyField for your datagrid. This will assign a unique key to every row in your grid <asp:DataGrid id=”dgAllRequirements” runat=”server” BackColor=”White” BorderColor=”Black” HorizontalAlign=”Center” AutoGenerateColumns=”False” DataKeyField=”SubStepID”> Then save the values you need in each row in hidden fields with unique names, using the same datafield you used for DataKeyField <asp:TemplateColumn HeaderText=”Inv”> <ItemTemplate> <input type=hidden name=”hidInventorySite<%#DataBinder.Eval(Container.DataItem,”SubStepID”)%>” value=”<%#DataBinder.Eval(Container.DataItem,”InventorySiteCode”)%>”> </ItemTemplate> </asp:TemplateColumn> Then access the hidden fields for the values you need private void dgAllRequirements_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEv

URL Authorization

These links should be of some help to you. http://support.microsoft.com/default.aspx?scid=http://support.microsoft. com:80/support/kb/articles/q306/5/90.asp&NoWebContent=1 gives an overview of .Net security in general including authentication and authorization http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide /html/cpconaspnetauthorization.asp gives an overview of authorization in particular. I have used Forms Authentication with UrlAuthorization on a number of occasions and have never found any cons to it and find it much easier to implement than more conventional methods. The immediately obvious advantages are You can control which users are allowed to access which urls or sub-urls in one single place, the web.config file which is a great help. All unauthorized users are taken to the login page (form) also specified in the web.config The login form is also provided with the originally requested Url so that the user will automatically be re-directed on autho

.Net debug or release

A description : - “See this http://weblogs.asp.net/jkey/archive/2003/11/23/39383.aspx His method is wrong, of course, but that should put you on the right track. The tricky part was not being able to unload the assemblies and not being able to read the assemblies without loading them into the App domain in .Net 1.1 I believe this problem has been solved in 2.0 (ReflectionOnlyLoad and ReflectionOnlyLoadFrom) Another link This is why I have to re-load the app whenever it reads the Dlls, to release the assemblies.” The code for telling the difference : - foreach (FileInfo FileInfoEach in DiScripts.GetFiles(“*.dll”)) { OneAssembly = Assembly.LoadFile(FileInfoEach.FullName); Object[] CustomAttributes = OneAssembly.GetCustomAttributes(false); bool IsDebuggable = false; foreach (Object CustomAttributein CustomAttributes) { if (CustomAttribute is DebuggableAttribute) if(((DebuggableAttribute)CustomAttribute).IsJITTrackingEnabled ) { IsDebuggable = true; break; } } DtDlls.Rows.Add(new object[

The .NET Framework, Visual Studio.Net and C#

I tried to look up a good reference for .NET or rather the .NET Framework as it is actually called and found this http://www.microsoft.com/net/basics.mspx But that seems more like something meant for the layman or client. This one is perfect http://msdn.microsoft.com/netframework/programming/fundamentals/default.aspx "The .NET Framework is a development and execution environment that allows different programming languages & libraries to work together seamlessly to create Windows-based applications that are easier to build, manage, deploy, and integrate with other networked systems. The .NET Framework consists of: The Common Language Runtime (CLR) A language-neutral development & execution environment that provides services to help "manage" application execution The Framework Class Libraries (FCL) A consistent, object-oriented library of prepackaged functionality" This link will help explain (or increase) the jargon a bit http://msdn.microsoft.com/library/def

Ajax.Net

[This and the following post were from an email and might seem a bit basic. It is meant for beginners] I looked up http://schwarz-interactive.de/ after I wrote to you and it IS a an Ajax component written for .Net As with all .Net names, it has been named Ajax.Net

Web Forms Page Processing and Control Execution Lifecycle

I’m giving both a quick reference as well as the MSDN links to the full information here. Web Forms Page Processing ASP.NET Page Framework Initialization The page’s Page_Init event is raised, and the page and control view state are restored. User Code Initialization The page’s Page_Load event is raised. Validation The Validate method of any validator Web server controls is invoked to perform the control’s specified validation. Event Handling If the page was called in response to a form event, the corresponding event handler in the page is called during this stage. Cleanup The Page_Unload event is called because the page has finished rendering and is ready to be discarded. Control Execution Lifecycle Initialize Load view state Process postback data Load Send postback change notifications Handle postback events Prerender Save state Render Dispose Unload

Control that caused the post-back

string EventTarget = Request[”__EVENTTARGET”] as string; if (EventTarget==null) EventTarget=””; if (EventTarget.IndexOf(“LbtnBeSecond”) > -1) { } Basically, Request[”__EVENTTARGET”] tells you which control caused the post-back. -- Request[”__EVENTTARGET”] doesn’t return a value when the form was submitted by a button In this case, one can find the button-name from the Request object (like in the old ASP days). -- Post-backs by buttons (‘submit buttons’) don’t set eventtarget. Only controls that use the __doPostback() method set it. -- ASP buttons render to HTML submit buttons. In this case <asp:button id=”btnSubmitSearch” runat=”server” Text=”Search” cssclass=”button” CausesValidation=”False” /> Renders to <input type=”submit” name=”Module36:btnSubmitSearch” value=”Search” id=”Module36_btnSubmitSearch” class=”button” /> Yes, JS and individual solutions are possible but FindTargetControl would essentially fail for any submit/ASP button. Instead, I can loop through the Req

New VS.Net file extensions

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\7.1\Languages\File Extensions\ That’s where you need to add an extra key in the registry if you need your VS to recognize new file types. Use the value from the existing file type whose formatting you want the new file type to have.

Best practices - ASP.Net and C# (personal list)

1. Dispose and release all memory intensive objects explicitly (using ‘using’ or using ‘dispose’ in the finally block) 2. Reduce database calls and unnecessary processing. Store all calculated values and other such small data in session or viewstate instead of querying them from the database or calculating them again and again. If any processing requires multiple database calls, try to do the processing within a stored procedure to reduce database calls. 3. Reduce the size of objects - retrieve only the data you need WHEN you need it. If you’re using datatables and datasets in .Net, remember to call .AcceptChanges() whenever you make some changes to them. Otherwise, these objects typically maintain all previous versions of data within them too. 5. Avoid post backs unless you need something from the session or the DB Nearly all the work done on the forms- enabling / disabling, selection / de-selection of checkboxes and rows on grids, launching Pop-Ups etc - can be done on the client sid

Navigating to the previous web form or web page

For example: To redirect a user back to search page from the results page if he wants to change the criteria. history.go(-1) and history.back() don’t usually work because your results page may have submitted or posted back. So most workarounds I have seen involved storing all the values of the previous web-form and then painfully reloading it. This one is so simple. I thought of it a couple of days back. I’m amazed I didn’t think of it before. It doesn’t even post back on button click! // Step 1: Count the post backs and store it in a hidden field private void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { HidPostBacks.Value = “1”; } else { int PostBackCount = int.Parse(HidPostBacks.Value); HidPostBacks.Value = (PostBackCount+1).ToString(); } } // Step 2: The html for storing the fields and calling the JS method <form id=”Form2” method=”post” runat=”server”> <input type=”hidden” id=”HidPostBacks” runat=”server” value=”0”> <input

Pro*C - Indicator Variables

Pro*C has some SQL syntax that cannot be directly converted to PL/SQL. A common example of this in our project is Indicator Variables. You must have frequently seen this kind of code - SELECT xyz INTO :host_var:indicator_var - in our Pro*C code: selecting one column into more than one variable. You can understand how this works by looking at http://www-db.stanford.edu/~ullman/fcdb/oracle/or-proc.html#indicator%20variables The simplest workaround, of course, is to assign the indicator variable - if you need one - after your select statement in your PL/SQL code.

SYS_REFCURSOR

SYS_REFCURSOR is a pre-defined weak REF CURSOR type that was added to the PL/SQL language in Oracle 9i Release 1 It can be used instead of the ref_cursor (or other similar types) that we once defined explicitly in earlier versions of Oracle.

oracle returning record type

oracle select from a RECORD oracle cursor RECORD TYPE oracle procedure record argument oracle RECORD oracle RECORD cursor oracle RECORD table cursor oracle RECORD to cursor oracle RECORDs oracle return data from a record oracle returning record oracle returning record object oracle returning record type OracleDataAdapter record OracleDataAdapter record type returning a record sql cursor “return just one record” sql type for record Did that make sense? Those are, quite simply, the various searches I attempted yesterday trying to find a way to work with an Oracle PL/SQL procedure that returned a record type as an out parameter. Apparently, it’s impossible. ODP.Net provides no way of working with one. Interestingly, there is no mention of in any of the references as to the impossibility of the task either. There’s tons of stuff about getting data into records but nothing about getting it out. Guess people don’t write about stuff they couldn’t do. So anyway, the workaround: FUNCTION readDa

DataFormatString - displaying dates and times in a datagrid

A common requirement from clients is to have dates (DateTime values) in MM-DD-YYYY format in grids and other DataBound objects. As we all know, the most common ways of doing this are by modifying the cell text in the DataBound event or by having a calculated column in your datasource. There is a much easier way - using the DataFormatString property of BoundColumn. For example, the following code <asp:DataGrid id=”DataGrid1” runat=”server” AutoGenerateColumns=False> <Columns> <asp:BoundColumn DataField=”Id” HeaderText=”Serial Number”></asp:BoundColumn> <asp:BoundColumn DataFormatString=”” DataField=”IssueDate” HeaderText=”Issue Date”></asp:BoundColumn> </Columns> </asp:DataGrid> Gives Serial Number Issue Date 1 8/25/2005 4:34:33 PM 2 9/4/2005 4:34:33 PM 3 9/24/2005 4:34:33 PM 4 10/4/2005 4:34:33 PM And this code <asp:DataGrid id=”DataGrid1” runat=”server” AutoGenerateColumns=False> <Columns> <asp:BoundColumn DataField=”Id” H

Javascript row selection (web datagrids) and maintaining selections across postbacks

Selecting and setting color for rows in datagrids (web) with javascript and maintaining selections across postbacks: - Pretty basic stuff but there are a few little tricks to it that can make life easier too - for the developers as well as the users. As always, I would recommend html controls as opposed to web controls when there is no need for server-side manipulation. There are two grids here - one with a single selection (radio buttons) and one with multi selection. Most of the code is self explanatory. In particular, notice the use of onpropertychange as opposed to onclick This ensures the firing of the event handlers under all circumstances (as in a radio button getting unchecked because of another one getting selected or a checkbox being unchecked by javascript). I’m giving all relevant code here. First the javascript <script> // Checking previously selected checkboxes function checkChkRequirements(Ids) { IdArr = Ids.split(‘,’); for (j=0; j <IdArr.length; j++)

Erroneous Size.Height (or width) for newly initialized windows control

From here The ‘x’ in the following code public class myPanel: System.Windows.Forms.Panel { protected Control inner; public myPanel(Control _ctrl) { inner = _ctrl; this.Controls.Add(inner); int x = inner.Size.Height; } } Will always show a value of ‘100’ despite whatever the actual value of Size.Height is. But if you run control through the ‘x=’ assignment statement after a quick watch on ‘inner’, you’ll get the right value. This can be fixed by calling the Control.CreateControl() method which causes the Size.Height to be initialized to the correct value. public class myPanel: System.Windows.Forms.Panel { protected Control inner; public myPanel(Control _ctrl) { inner = _ctrl; inner.CreateControl(); this.Controls.Add(inner); int x = inner.Size.Height; x=55; } }

Reversing strings - C#

string SomeStr = “SomeStr”; char[] OrigChars = SomeStr.ToCharArray(); Array.Reverse(OrigChars); Label1.Text = new string(OrigChars);

Avoiding dynamic SQL

Performance of static SQL is generally better than dynamic SQL as we all know. Here are a few simple ways to avoid writing dynamic SQL in circumstances where dynamic SQL can seem inevitable This first one is a simple condition where based on the value of a parameter, the SQL needs to use either the parameter or a constant. Hence the statement is modified within the condition appropriately. IF (alt_id > 1) THEN serialstmt := serialstmt || ‘SII.alt_id = ‘ || alt_id || ‘ ‘; ELSE serialstmt := serialstmt || ‘SII.alt_id = 1 ‘; END IF; What you see below is a static SQL implementation of the same. SII.alt_id IN( SELECT as_alt_id FROM DUAL WHERE as_alt_id > 1 UNION SELECT 1 FROM DUAL WHERE as_alt_id <= 1) AND The next one, a more complex example, involves a conditional string comparison - another common scenario. IF (job_nbr IS NOT NULL AND job_nbr != “) THEN serialstmt := serialstmt || ‘AND SSEWO.job_nbr = “” || job_nbr || “” ‘; END IF; Ca

javascript - Loading and clearing dropdowns

A typical problem wherein a series of controls - in this case a textbox and two drop downs - needed to be enabled or disabled and loaded with data depending on the value in the previous control. The drop downs are loaded on focus and cleared when the textbox changes, all in javascript. No postbacks unless data has to be loaded. <%@ Page language=”c#” Codebehind=”WebForm1.aspx.cs” AutoEventWireup=”false” Inherits=”WebApplication2.WebForm1” %> <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN” > <HTML> <HEAD> <title>WebForm1</title> <meta name=”GENERATOR” Content=”Microsoft Visual Studio .NET 7.1”> <meta name=”CODE_LANGUAGE” Content=”C#”> <meta name=”vs_defaultClientScript” content=”JavaScript”> <meta name=”vs_targetSchema” content=”http://schemas.microsoft.com/intellisense/ie5”> <script> function Populate(nIndex) { if (((nIndex == 1) && (document.forms[0].HidDd1Pb.value == “1”)) ((nInd

Hiding a datagrid with Javascript, coding for onmouseover in a datagrid

Put very simply, the DataGridItem = <TR> So a simple foreach (DataGridItem Item in DataGrid1.Items) { Item.Attributes.Add(“onmouseover”, “alert(‘”+Item.Cells[0].Text+”’);”); } Will show an alert with the value in the first cell when you move your mouse over the row. A very simple example! But the concept can be used for much more complicated requirements liking changing background colours or ‘binding’ textboxes outside the grid to values inside it. The hiding involves nothing but wrapping the grid an <a> tag and setting it’s style. Complete code <%@ Page language=”c#” Codebehind=”WebForm1.aspx.cs” AutoEventWireup=”false” Inherits=”WebApplication2.WebForm1” %> <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN” > <HTML> <HEAD> <title>WebForm1</title> <meta name=”GENERATOR” Content=”Microsoft Visual Studio .NET 7.1”> <meta name=”CODE_LANGUAGE” Content=”C#”> <meta name=”vs_defaultClientScript” content=”JavaScript”>

Custom DHTML Tree View

Introduction This document is divided into five sections The problem statement Constraints The resolution The code Generated data The problem statement The requirement involves building an expandable and collapsible tree view on a web page for an indefinite number of nodes and inner nodes, similar to the folders and files in a file system. The depth into which a particular branch goes can also vary from node to node. Hence the data is not in the form of normalized set of tables but in the form of an array of strings each of which specifies one complete branch. The nodes in a branch are separated by ‘/’s and each branch may or may not have nodes in common with other branches (see generated sample data in the end) Constraints The Microsoft tree view is not acceptable because it does not meet the required performance rps and requires a postback to the server for every click on a node. Other commonly available VB and DHTML options involve complex implementation methods running into many h

Archive

Show more