AWG Blogs

Saturday, November 30, 2013

Create empty file with bcp

I wasn't sure if multiple statements (using semicolon as delimiter) could be passed to bcp, so I tried it, specifically prepending a DECLARE statement and it worked, in this case for creating an empty file:
DECLARE @FilePath VARCHAR(1000)
DECLARE @FileExists int
DECLARE @nulltable TABLE ( foo integer)
SET @FilePath = 'C:\my\path\somefile.csv'

exec master.dbo.xp_fileexist @FilePath, @FileExists OUTPUT
if not @FileExists = 1 
begin
declare @bcpCommand varchar(255), @Result int
set @bcpCommand = 'bcp "DECLARE @nulltable TABLE ( foo integer); Select * from @nulltable" queryout "' + @FilePath + '" -c -t, -T -S '
exec @Result = master..xp_cmdshell @bcpCommand  --, no_output
end

Wednesday, August 7, 2013

Get Value of Form Element

I had names to compare only (as they are generated from DB). I needed the value regardless of element type; most would try to detect type then get the value.

For now I will settle on a one liner expression, and see how it goes in testing:

 $("input[name='NameOfElement']:checked").val() || document['formName']['NameOfElement'].value || false

This should handle radio buttons and checkboxes first (if checked), then selects and inputs, then false. My use case doesn't require comparing values of textareas or multiselects, so I am not accounting for them for now.
Note: I found the above to cause "Do you want to continue running scripts on this page?" messages on old clients, namely IE 7 or 8 on single core Windows XP PCs. So I was forced to replace the above jQuery-reliant code with the following more verbose pure JavaScript:
if ( ! ( (document['Form1']['ItemFoo'].length && document['Form1']['ItemFoo'][0].type=="radio" && myGetSelectedRadioValueByName('ItemFoo')=="Yes") || (!document['Form1']['ItemFoo'].disabled && document['Form1']['ItemFoo'].type=="checkbox" && document['Form1']['ItemFoo'].checked==true && document['Form1']['ItemFoo'].value == "Yes") || (!document['Form1']['ItemFoo'].disabled && document['Form1']['ItemFoo'].type!="checkbox" && document['Form1']['ItemFoo'].value == "Yes"))){ var elems = document.getElementsByName('TargetShowHideElement'); for (var i = 0; i < elems.length; i++) { elems[i].disabled= false; } }


A side note about the above: It is a work in progress; the language-specific expressions are generated from a DSL (a table of variables and corresponding conditions), in a manner similar to a suggestion by "Doc Brown" at http://programmers.stackexchange.com/questions/182025/creating-huge-decision-tree

Friday, June 21, 2013

Disabling Siblings of Selected Radio Button

I couldn't find a "contains" selector that applied to html elements, hence the following hack less elegent (more verbose than it should be) method that functionally and stylistically disables all li containers that don't contain the radio button that's selected:
var enableOnlySelectedListItem = function(parentId, radioItemName) {
     $('#' + parentId + ' input:radio[name=' + radioItemName + ']')
         .on('click', null,"",function (event) {
            $(this).closest('ul')
                .find('input[name=' + radioItemName + ']')
                .not(this)
                .parent()
                .find(':input')
                .not('input[name=' + radioItemName + ']')
                .prop('disabled', true)
            .end()
            .end()
            .addClass('disabledtext');    
                
            $(this).closest('li')
                .find(':input')
                .prop('disabled', false)
            .end()
            .removeClass('disabledtext');    
                
             event.stopPropagation();
     });
};

Sunday, May 19, 2013

Installing Stunnel on CenOS 5

Download tar.gz file from http://www.stunnel.org/downloads.html?extra=/source.html
to ~/temp
did: 
gzip -dc stunnel-4.56.tar.gz | tar xvf -
cd stunnel-4.56
./configure
make
make install

vi /usr/local/etc/stunnel/stunnel.conf-sample
add the line
fips = no
change cert = line to read
cert = /usr/local/etc/stunnel/stunnel.pem
adjust service section, e.g. for forwarding smtp securely

cp /usr/local/etc/stunnel/stunnel.conf-sample /etc/stunnel/stunnel.conf
cp /etc/stunnel/stunnel.conf /usr/local/etc/stunnel/stunnel.conf
#this last one to satisfy stunnel from cmd line, the prior for the service
#perhaps should make them hard linked

cp /usr/local/share/doc/stunnel/examples/stunnel.init /etc/init.d/stunnel
cd /etc/init.d
chmod 755 stunnel

vi stunnel
modify top of file to read:
#! /bin/sh -e
# description: stunnel Start Stop Restart
# processname: stunnel
# chkconfig: 234 20 80

then in startdeamons() change the install line to read:
install -d -o nobody -g nobody /var/run/stunnel

save file
do:
echo "ENABLED=1" > /etc/default/stunnel

Disable sendmail
chkconfig sendmail off; service sendmail stop

Enable stunnel
chkconfig --add stunnel
In case tests are running:
pkill stunnel 
service stunnel start

References:


Sunday, May 5, 2013

Using vb2js

This is one of the only tools I've found to automatically convert VBA files to .js files. YMMV.

- Download via svn. see https://code.google.com/p/vb2js/source/checkout

- Download Guava (currently guava-14.0.1.jar)  - https://code.google.com/p/guava-libraries/; place downloaded file in 'src' folder of vb2js download

- Open a text editor and insert this code
package com.google.vb2js;
import java.util.*;
import java.io.*;

public class MyVbaJsConverter {
  public static void main(String[] args) throws FileNotFoundException, IOException {
    if (args.length == 2) {
   String entireFileText = new Scanner(new File(args[0]))
  .useDelimiter("\\A").next();
   FileWriter fstream = new FileWriter(args[1]);
   BufferedWriter out = new BufferedWriter(fstream);
   out.write(VbaJsConverter.convert(entireFileText));
   out.close();

    }
  }
}
- Save the file as "MyVbaJsConverter.java" in the same directory as the unpacked vb2js java files (e.g. in D:\temp\vb2js-read-only\src\com\google\vb2js) - Create a text file with the following content. Save it as ...\src\testInput.bas
Dim MyList As String
Dim MyNum As Integer
- Make sure JDK is installed and JDK bin folder is in path environment variable - Open a command prompt and change to src folder. - Execute the following commands:
d:\temp\vb2js-read-only\src>javac -cp guava-14.0.1.jar com\google\vb2js\*.java
D:\temp\vb2js-read-only\src>java -cp .;guava-14.0.1.jar com.google.vb2js.MyVbaJsConverter testInput.bas testOutput.js
- Open testOutput.js and verify that VBA was converted.

refs: http://abhinandanmk.blogspot.com/2012/05/java-how-to-read-complete-text-file.html
http://www.roseindia.net/java/beginners/java-write-to-file.shtml

Thursday, April 18, 2013

Tomcat Hello World Servlet

Here's a no-IDE quick-start how-to. Create the following directories:

c:\users\John Smith\Documents\scratch\helloTomcat\src
c:\users\John Smith\Documents\scratch\helloTomcat\dist\WEB-INF

open NotePad++ and create the following two files.

c:\users\John Smith\Documents\scratch\helloTomcat\dist\WEB-INF\web.xml

<!DOCTYPE web-app PUBLIC
  '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN'
  'http://java.sun.com/dtd/web-app_2_3.dtd'>
<web-app>
  <servlet>
    <servlet-name>mihello</servlet-name>
    <servlet-class>HelloServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>mihello</servlet-name>
    <url-pattern>/mihello</url-pattern>
  </servlet-mapping>
</web-app>
c:\users\John Smith\Documents\scratch\helloTomcat\src\HelloServlet.java
import java.io.*;

import javax.servlet.http.*;
import javax.servlet.*;

public class HelloServlet extends HttpServlet {
  public void doGet (HttpServletRequest req,
                                         HttpServletResponse res)
        throws ServletException, IOException
  {
        PrintWriter out = res.getWriter();
        out.println("Hello, You!");
        out.close();
  }
}
Open a command prompt
C:\Users\John Smith\Documents\scratch\helloTomcat\src>javac -cp "C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar" HelloServlet.java
C:\Users\John Smith\Documents\scratch\helloTomcat\src>mkdir ..\dist\WEB-INF\classes
C:\Users\John Smith\Documents\scratch\helloTomcat\src>copy *.class ..\dist\WEB-INF\classes
C:\Users\John Smith\Documents\scratch\helloTomcat\src>cd ..\dist
C:\Users\John Smith\Documents\scratch\helloTomcat\dist>jar cvf web-arc-test.war
Open a command prompt as Administrator
C:\Users\John Smith\Documents\scratch\helloTomcat\dist>copy web-arc-test.war "C
:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps"
open browser and browse to http://localhost:8085/web-arc-test/mihello
Note: change port to whatever tomcat is running on.
Refs:
http://keyboardsamurais.de/2004/01/15/tomcat_tutorial_helloworld_for_complete_fools_-_english/
http://stackoverflow.com/questions/7924687/compiling-a-simple-hello-world-servlet-into-a-war-for-tomcat
http://www.avajava.com/tutorials/lessons/how-do-i-create-a-war-file-using-the-jar-command.html

Friday, April 5, 2013

Get Property by an Attribute Property Value using LINQ

//look up the attribute matching the listid using Reflection and LINQ
                Type dtoType = typeof(AppInitParamsDTO);
                PropertyInfo pi = dtoType.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                            .Where(
                            x => typeof(AppInitParamsSettingsListNameAttribute)
                                .GetProperty("ListName")
                                .GetValue(Attribute.GetCustomAttribute(
x, typeof(AppInitParamsSettingsListNameAttribute)), null).ToString()
                                == listId).First();

Tuesday, March 26, 2013

JSONSelect Usage

For the simple use case of verifying the existence of a "record" in a JavaScript object, you typically need to iterate through all items. There is a one-liner approach though, thankfully.

Say you want to verify that an ID exists in
 "Body": {
  "GetListCollectionResponse": {
   "GetListCollectionResult": {
    "Lists": {
     "List": [
      {
       "ID": "{B8B000CC-EB90-4B3D-9A44-79B8A9CFCAAC}",
       "RequireCheckout": "False",
       "EnableMinorVersion": "False",
...
Verify existence with the following function:
ListExists = function(listGuid) { //search spsvcListColXmlJson for match
  var arr = JSONSelect.match(":has(:root > .ID:val(\""+listGuid+"\"))", 
   spsvcListColXmlJson.Body.GetListCollectionResponse.GetListCollectionResult.Lists);
  var retval = arr.length>0;
  return retval; 
 };
Test:
test('List Guid found in Lists collection', function() {
 ok(ListExists("{B8B000CC-EB90-4B3D-9A44-79B8A9CFCAAC}"),"list should exist");
});

Thursday, February 28, 2013

DB Access Account error when Adding WFE

If you get this error when attempting to add a WFE to a farm:

"SharePoint Products and Technologies Configuration Wizard"
"The username entered must be the same as the database access account for the server farm you wish to join. Either choose NT AUTHORITY\NETWORK SERVICE as the username or choose a different database name"

try changing the user account used for the Timer service and Central Admin app pool. Supposedly this is the account specified at installation AKA server farm account or AKA Database Access Account (as in the error message).

Confusing, I know.

This does the trick:

stsadm -o updatefarmcredentials -userlogin -password

iisreset /noforce

 http://technet.microsoft.com/en-us/library/cc288991(v=office.12).aspx

Note: you may also need to enable the SQL Server Browser service on the CA server.

Friday, February 15, 2013

Bind ViewModel Declaratively with Caliburn.Micro in Non-Caliburn.Micro App

I have an existing Silverlight App with Frame based navigation and the app is fairly stable. I wanted to look into logging interception of ViewModels and that is when I started testing Caliburn.Micro (per an answer to my question here). My aim is to gradually migrate pages over to the Caliburn.Micro framework, but not have CM take over the App at first (i.e. set the RootVisual). The closes discussion on the web I could find regarding this scenario was http://caliburnmicro.codeplex.com/discussions/260738. To do a proof-of-concept I simply combined the files from the Caliburn.Micro.ViewFirst sample project with a SL Nav template project:

- Create a new "Silverlight Navigation Application" project
-Add existing files from ViewFirst sample: IShell.cs, MefBootstrapper.cs, and ShellViewModel.cs (change namespaces if desired)
- Add necessary references to MEF and Caliburn.Micro
- In MefBootstrapper, remove the OnStartup override method, since we are not setting the rootvisual, but instead letting the App.xaml do that. Note I thought it was necessary to also override the constructor and set "base(false)" but it seems to work either way, so I left it out.
- Copy the StackPanel element and its content from ShellView.xaml into the ContentStackPanel of About.xaml
- For the declarative binding of VM, also add the following also to About.xaml:     cal:Bind.Model="Shell"  xmlns:cal="http://www.caliburnproject.org"
- At the top of the App constructor of App.xaml.cs add:             new MefBootstrapper();
- Press F5, click "About" and notice that you have a working Caliburn.Micro ViewModel View with Actions all wired up automatically!

Monday, February 11, 2013

IsolatedStorageException - "Initialization Failed"

I got this IsolatedStorageException - message: "Initialization Failed" - when using Enterprise Library. The line giving the error is in StorageAccessor.Silverlight.cs
            this.store = IsolatedStorageFile.GetUserStoreForApplication();
I've gotten this error before in other circumstances, and usually occur right after I delete the Isolated Storage for a particular URL and reopen the app.

Tried rebooting, recompiling, reinstalling Silverlight runtime. Finally what worked was deleting this folder: C:\Users\User.Name\AppData\LocalLow\Microsoft\Silverlight

Apparently there is some corrupted state left over in there. I also noted that around this time I was unable to delete other app stores.

Thursday, January 24, 2013

XML/Javascript Mapping with Jsonix

I needed a way to edit an XML config pulled from a SharePoint List (via SPServices). So that's when I found Jsonix, which so far in my testing appears to do the job quite well.

The steps I took were:
- Load the XML in Visual Studio and click XML, Create Schema. This created two .xsd files "MySettings.xsd" and "MySettings1.xsd" (in the same directory) as Visual Studio 2010 split them out by namespace apparently. At any rate, what I had to do was edit the xs:import element in the parent XSD, adding a schemaLocation attribute with the unqualified name of the second .xsd file.

- Downloaded jsonix-scripts-1.2-all.js and jsonix-full-1.2.jar   from http://repo2.maven.org/maven2/org/hisrc/jsonix/  -- note, I tried 1.0 per the how-to on the author's site, but it didn't seem to work for me (got errors which I didn't have the time to troubleshoot); however 1.2 worked like a charm, although the generated objects are rather cryptic.

- Ran C:\temp\jsonix-samples-po-1.0>java -jar lib/jsonix-full-1.2.jar -d src/main/webapp/js src/main/resources/MySettings.xsd
This generated two folders with a Mappings.js in each folder, corresponding to the two .xsd files. I combined these two .js files into one, putting the code from generated\Mappings.js at the top of the file and the code from settingsuri\Mappings.js (assuming "SettingsURI" is the root xmlns) at the bottom.

- I then uploaded my sample .xml and the .js files to the SharePoint list and placed the following code in a test .html page.


<script type="text/javascript" language="javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript" language="javascript" src="jquery.SPServices-0.7.2.min.js"></script>
<script type="text/javascript" language="javascript" src="jsonix-scripts-1.2-all.js"></script>
<script type="text/javascript" language="javascript" src="BothMappings.js"></script>

<script type="text/javascript" language="javascript">

    $(document).ready(function () {
 
var context = new Jsonix.Context([ settingsuri]);

var unmarshaller = context.createUnmarshaller();
var myURL = "MySettings.xml";
unmarshaller.unmarshalURL(myURL,
function (data) {
var objectFromURL = data;
alert(objectFromURL);
});

    });

</script>

- Turn on Debugging in IE Developer tools and place a breakpoint in the callback. The local watch clearly shows objectFromURL reflects the mappings of the XML file. Pretty sweet.

Sunday, January 13, 2013

Dev on Alternate Machine

This is for when you want to work on a different SharePoint 2007 dev machine but not have to change host name configuration entries in your Silverlight code.

- edit the Windows hosts file adding
127.0.0.1 yourPrimaryServerName

- add yourPrimaryServerName as a public url for the intranet zone of your web app in the alternate access mappings

- add a host header value of "yourPrimaryServerName" to the site's IIS 6 configuration

- set DisableLoopbackCheck see http://support.microsoft.com/kb/896861
- add the following files to c:\inetpub\wwwroot (or a subdir, check IIS for the actual root dir the 80 site)

clientaccesspolicy.xml

<?xml version="1.0" encoding="utf-8" ?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>

<grant-to>
<resource include-subpaths="true" path="/"></resource>
</grant-to>
</policy>
</cross-domain-access>

</access-policy>

crossdomain.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- The file must be configured to allow access to the service from any other domain,
or it is not recognized by Silverlight 4.
Save the crossdomain.xml file to the root of the domain where the service is hosted.
If, for example, the service is hosted in http://fabrikam.com,
then the file must be located at http://fabrikam.com/crossdomain.xml.
-->
<!DOCTYPE cross-domain-policy SYSTEM
"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-http-request-headers-from domain="*" headers="*"/>

</cross-domain-policy>
ref