In successfully installed a Canon LBP 6000 on my Mac Mini and was able to print to it. I then turned on printer sharing and shared it. I was able to see the shared printer listed on my Macbook Air, but when I tried to print to it over the network it would say processing for a long time, and then switch to paused. When I checked the printer status on the Mac Mini, there was no sign that the print job had ever been received.
Long story short, it turns out that the problem occurred because I had previously connected the LBP 6000 to the Macbook Air by USB and installed the Canon CAPT driver for the printer, and for some reason this caused the Macbook Air to assume the printer was directly connected when I tried to use the remote printer. You can see that this is happening by going to Apple->About this Mac->System Report and then looking at Printers, and then looking at the URI entry for the remote printer. For remote printers the URI should be something sort of like this:
2014-03-15
Fixing can't print to shared Canon LBP 6000 in Mac OS X
Posted by AndyfromTucson at 07:25 0 comments
Labels: mac
2014-01-21
Using autofs to fix a number of issues with using AFP network shares in Mac OS X
My wife and I share a Macbook Air with Mac OS X Lion using fast user switching. We both work with files stored on an AFP network share from our family Mac Mini using the MBA. We were running into the following issues with this setup:
- The network share ("family-network-share") from the Mac Mini would frequently get dropped and have to be remounted manually. Often the original mount point stealthily persisted in /Volumes (not shown in Finder, but shows up when you do an ls in Terminal) so that when you remounted the share it got the name family-network-share-1 (as shown with ls in Terminal), which broke any applications or scripts that used the share.
- If one of us mounted the network share it would show up under Volumes (and on the desktop) for the other user, but it would be unaccessible to the second user (as indicated by a red circle badge on the mounted share in Finder) because permissions were restricted to the person who originally mounted the share.
- When the second person mounted the share it would show up in Finder and the desktop as a second instance of the share with the same name, but in Terminal it got the name family-network-share-1 because the /Volumes mount point was already taken by the first user. This made it impossible to have any scripts or applications use the network share because you couldn't be sure what its path would be for a particular user.
sudo nano /etc/auto_master
/- auto_my_mount_map_file
sudo nano /etc/auto_my_mount_map_file
/Users/andy/family_share_mount_point -fstype=afp afp://username:password@share_local_IP_address/family-network-share
Then load the new mount map file by reloading autofs like so:
sudo automount -vcThe first thing you are going to do is look for the new mount in Finder, and when you do that you will think it didn't work because it won't show up in Finder. However, it is working, as you can demonstrate by navigating to the new folder in Terminal:
cd /Users/andy/family-network-share
lsAfter you do that, go back to Finder and voila, now it shows up. My theory is that autofs doesn't bother to mount the network share until some program tries to use it. To avoid the problem of the folder not being visible in Finder after a reboot I wrote a two line BASH script to cd to the share folder and then list its contents using ls, and then put that script in each user's login items under System Preferences - Users and Groups.
UPDATE 2016-01-13:
After coming back from a long trip and setting up our network again from scratch, I was having trouble getting this to work. The specific issue was that one user, or both users, would be locked out of the mount point for the network share because the owner of the mount point was randomly (at least I couldn't detect a consistent pattern) being changed to root by the system. This problem appeared to go away after I took the following steps:
- I put the mount points one more level down in the directory structure, i.e. instead of /Users/andy/my_mount_point I made it /Users/andy/Famly_shares/my_mount_point.
- I did not create the mount point manually, I just put it in the auto_my_map_point file.
- I very excluded the parent folders of both users' mount points from Spotlight (System Preferences -> Spotlight -> Privacy). It can be confusing because privacy exclusions set by both users seem to show up in both user's Spotlight settings, and it shows only the final folder of the excluded path, but if you hover over the folder name for a few seconds a tooltip shows up with the full path. My reason for trying this was that autofs creates a mount point when a user tries to access the mount point, so maybe Spotlight indexing activity was causing the share to be mounted as root and locking users out.
- I reactivated my old login script that changed directory into the mount point (see above) even though under El Capitan the mount point showed up without it. Once again, my theory was that the first user to access the mount point wins, so the login script to go into the folder hopefully prevents some root process from getting there first.
Posted by AndyfromTucson at 06:30 1 comments
Labels: mac
2013-10-23
Setting up Mac OS X Snow Leopard as an Apache, MySQL, PHP (MAMP) web server
When my old Ubuntu on a laptop web and file server died I decided to set up my Mac Mini with Snow Leopard as its replacement rather than finding another old laptop and building a new Linux server on it. I was afraid setting up an Apache, MySQL and PHP stack on Mac OS X would be complicated and messy, but it turned out to be pretty straightforward thanks to some good guides on the web.
My first step was to follow this how-to from the "Coolest Guides on the Planet" website:
Install and configure Apache, MySQL & PHP on OS X Lion 10.7 and 10.6
Then I followed another guide by the same person for setting up phpMyAdmin:
Installing phpMyAdmin on Mac OSX 10.8 Mountain Lion & 10.7, 10.6
I then went ahead and imported the backup of the database for my home-brewed web apps into MySQL using phpMyAdmin, and copied my PHP files into the web server directory and tested my apps. I quickly ran into a problem where apps that had been working for years starting throwing fatal errors (sorry, I didn't write down what they were). After poking around on the web I discovered that the MySQL installer you download from Oracle has STRICT_TRANS_TABLES turned on by default, which can cause problems for apps developed on Ubuntu because STRICT_TRANS_TABLES is turned off by default in Ubuntu. I followed the directions on this blog post to turn off STRICT_TRANS_TABLES and then everything worked:
MySQL Strict Mode on OS X
After that, everything worked great.
What I learned about file sharing and permissions on Mac OS X Snow Leopard when I set it up as a file server for multiple users
For years I used an old laptop running Ubuntu as a combination web server and file server. It died a few weeks ago, and rather than find another old laptop and building another Linux server I decided to just set up my existing Mac Mini with (non-Server) Snow Leopard as a file server that my wife and I could access. Because it didn't "just work" I thought I would write down what I learned in the process. I have no idea how much of this is true for later versions of Mac OS X, so your mileage may vary on later versions.
My first thought was to see if I could get it to "just work." I plugged an external drive with the family files into the Mac Mini, turned on file sharing in System Preferences - Sharing while logged in as me, and then designated the top level folder on the external drive as a shared folder, and then in the Users box in System Preferences - Sharing I gave read and write permissions to my wife and I, and no access to Everyone. I went and tested accessing the shared folder over the network as both myself and my wife, and everything seemed to work. Great! But then, just out of paranoia, I tried accessing the folder over the network without entering a username and password, and discovered that anyone on the network could not only see the folder and its files without entering a username and password, anyone on the network could modify any of the files. WTF? After a lot of research and poking around I finally figured out the following.
1. In Mac OS X Snow Leopard external drives have the property "Ignore ownership on this volume" turned on by default on the drive's Get Info screen, and when that is checked any and all users, including guest or nobody, are treated as the owner of every file and folder on that drive.
I guess this is so that if someone plugs a USB drive into a Mac with multiple user accounts then all the users on that computer can access it. Which seems reasonable enough, until you bring file sharing into the picture:
2. If you share a folder on an external drive that has "Ignore ownership on this volume" turned on then anyone on the local network can mount that folder, and read and write to every file in that folder, without entering any credentials and regardless of what permissions you set on the folder or its files.
My theory is that Mac OS X file sharing relies entirely on the basic Mac OS X permissions system to control access to folders shared using file sharing, so if the "Ignore ownership on this volume" box is checked for an external drive, and you designate a folder on that drive as a shared folder, then Mac OS X concludes that since ownership is ignored on that drive no credentials are required to read and write to files in the shared folder.
The obvious next step was to uncheck "Ignore ownership on this volume" for the external drive and try sharing the folder again, with permissions on the "Get Info" dialog for that folder set to Read & Write for myself and my wife, and No Access for everyone. The group "staff" appeared on the list, but there was no "No Access" option for staff, so I left it at "Read only." After I did this the shared folder was no longer visible to people who connected to the machine without entering credentials, so one issue was solved.
Now that I had the shared folder on the external drive locked down so only my wife and I could access it I proceeded to test reading and writing files as myself and my wife. Here is what I observed when the "Get Info" permissions for the shared folder were set to Read & Write for both my wife and myself, the staff group was set to "Read only" and the everybody group was "No access":
- I could open and modify existing files, and save new files.
- My wife could open existing files I had created, but couldn't modify them.
- My wife could save new files, but I couldn't modify any new files she created.
- Looking at Get Info for a file created by one user showed that that user had Read & Write privileges, staff had Read only, and everyone had Read only.
4. In the non-Server version of Snow Leopard the only way to set inheritable permissions for a shared folder is by setting ACL permissions using the chmod command in Terminal.
Turns out Mac OS X has two different permissions systems, POSIX (the traditional *nix permissions system) and ACL (Access Control Lists). There is no way to set inheritable permissions for a folder using POSIX, but it can be done with ACL. Here is a article about the basics of ACL:
Introduction to OS X Access Control Lists (ACLs)
sudo chmod -R +a "group:my_new_group allow list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,file_inherit,directory_inherit" /Volumes/my_external_drive/the_folder_I_want_to_share
See the chmod man page for the details on the syntax for this command. If you don't run this as sudo then ACL permissions will *not* be set on files and folder you don't own, which can lead to confusing problems for users. The -R option means recursive, so the ACL will be set on all sub-folders and files.
A file or folder can have multiple ACLs piled one on top of another, which the operating sifts through using some order of precedence. This can lead to confusing problems for users. One easy way to start fresh with ACLs on a folder is to run this command which recursively removes all ACLs in and under the folder:
sudo chmod -RN /Volumes/my_external_drive/the_folder_I_want_to_share/
Then run your chmod command to set fresh ACLs for the folder.
Posted by AndyfromTucson at 04:56 0 comments
Labels: mac
2013-10-20
How to find deep sky objects for newbies
I took up amateur astronomy last year, and at the beginning I had a very hard time finding deep sky objects like galaxies, globular clusters, etc with my new telescope (an Orion XT8). Now that I have figured out how to quickly navigate to faint fuzzies I thought I would write down my method for other beginners.
Here are the tools you need for my method:
- Telescope.
- A 9x (or close to it) right angle correct image finderscope (RACI) with crosshairs.
- A green laser pointer (GLP) finder (preferred) or a red dot finder
- SkySafari+ on iOS (you could use some other apps or a star chart instead).
- Turn on Night (red) mode in SkySafari+ and dim your screen so it won't ruin your night vision.
- In the SkySafari+ settings adjust what magnitude stars get displayed so that the sky shown in SkySafari+ looks looks like what you see looking up. If SkySafari+ shows a lot of stars that are too dim for you to see on the sky it will be very hard to navigate, so you have to get it matched up to what you can see.
- Look up the deep sky object in SkySafari+ and center it on the screen.
- See what constellation the deep sky object is near in Sky Safari+, and then find that constellation on the sky. Move your telescope so it is roughly pointing towards that constellation. No need to be precise yet.
- Look up at the constellation and get oriented to the stars in constellation.
- Go back to SkySafari+ and mentally make a simple shape (line, triangle, or polygon) using your deep sky object as one corner and the nearest stars as the other corners. Coming up with this shape is the key to the whole process, so find a simple pattern and commit its shape to memory. I find that for some reason it helps to mentally verbalize the pattern, i.e. mutter to yourself something like "a long skinny triangle with the deep sky object at lower corner of the base"
- Move your telescope and place your red dot or laser beam so that it makes the same simple shape on the sky. Look back and forth between SkySafari+ and the sky and tweak your telescope position until the proportions and angles of your simple shape match between the sky and SkySafari+. The key to this technique is that your brain is naturally good at recognizing when two shapes look the same, so go back and forth until the match looks as good as you can get it.
- Once you have the telescope positioned so that your red dot or laser beam makes the same shape with surrounding stars go back to SkySafari+ and turn on the 5 degree crosshairs:
- Tap the upper right hand corner of the screen. This will open up a dialog that looks like this:
- Tap the "Rings" button under 5 degrees. This will place a 5 degree wide crosshair on the screen.
- Tap anywhere on the screen to exit the dialog.
- Center the crosshair on your deep sky object in SkySafari+, and then zoom in until the edges of the crosshair touch the edge of the screen. Now SkySafari+ is more or less displaying what you should see looking through your right angle correct image finder scope (plus or minus a degree or two).
- Now that you have your finder scope in the right area you need to get oriented to the stars visible in the finder scope. Look back and forth between your finder scope and SkySafari+ looking for single stars and/or simple patterns of brighter stars (like triangles, lines, or simple polygons) that you can find in both views. Don't worry about the deep sky object for the moment, just look for one or more star patterns you can find in both views. Be patient if at first you don't find any matching patterns and resist the temptation to move the telescope to look around; it often takes a few looks back and forth for a pattern to jump out at you. In this case there is a single very bright star that can be used as one calibration point, and two distinctive triangles of stars that can be used as others:
- Once you have identified one star or star pattern you can see in both SkySafari+ and your finder scope tweak the position of your telescope until that patterns sit in the same relative position in both your finder scope view and SkySafari+ crosshairs, i.e. if the pattern is near the edge in the upper left in SkySafari+, move the telescope so it is near the edge in the upper left in the finder scope.
- Now that you have your finder scope view more or less synced with your SkySafari+ view, repeat the earlier process of making a simple mental shape (triangle, line, etc) using your deep sky object and nearby stars in SkySafari+. Once again, coming up with the mental shape is key, and it may help to verbalize the shape under your breath.
- Move your telescope to make the same simple pattern with the finder scope crosshairs standing in for the faint fuzzy.
- Look through the telescope eyepiece; your deep sky object should be visible. Globular clusters and open clusters should be pretty easy to spot. Many galaxies and nebulas are very faint and look like almost invisible wisps of milkiness. Don't expect to see bold color images like you see in pictures.
- M108 in Sky Safari:
- What M108 might look like through the eyepiece:
Posted by AndyfromTucson at 05:37 0 comments
Labels: Astronomy
2013-06-19
Thunderbird "Work Offline" stops working after deleting an account
I was using Thunderbird (v14) to work with two different IMAP accounts. I recently shut down the first account (as in the first IMAP account I added to Thunderbird), and wanted to get Thunderbird to stop trying to get mail from that account on startup, when checking mail, and when going to "work offline." I tried just deleting the account (Tools -> Account Settings -> Account Actions -> Remove Account), which worked to delete the account from Thunderbird, but after that Thunderbird suddenly stopped downloading messages from the server to work offline with my remaining account. I would click the "work offline" icon, and it would go offline, but when I tried to open a message Thunderbird would say that the message contents had not been downloaded from the server. I played around with the Synchronization & Storage settings to no avail. Here is what ended up working for me to solve this.
- I restored the prefs.js in my profile directory from a backup. This got me back to where I had been before I deleted the first account, and back to the original problem of getting Thunderbird to not check for mail on the deactivated account.
- I found this forum thread on the topic of getting Thunderbird to not check an account for new mail:
http://forums.mozillazine.org/viewtopic.php?f=39&t=635510&start=15 - I followed one person's advice from the thread to delete the deactivated account from the "mail.accountmanager.accounts" value in prefs.js (while Thunderbird was shut down) like so:
Before edit (account enabled):
user_pref("mail.accountmanager.accounts", "account1,account2,account3");
after edit (account disabled):
user_pref("mail.accountmanager.accounts","account3"); - Note that figuring out which account is which in prefs.js takes a little scavenger hunt because the server information is saved under "identity" and then the identity is linked to the account. I figured out that my deactivated account was listed in prefs.js as both account1 and account2 (go figure).
- I then also edited the value of mail.accountmanager.defaultaccount in prefs.js so that my remaining IMAP account was listed as the default account, like so:
user_pref("mail.accountmanager.defaultaccount", "account2"); - After I did this Thunderbird stopped trying to check for mail on my deactivated account, and, at least initially, successfully downloaded the contents of all my messages when I chose "work offline."
- However, later in the day kept having intermittent problems with message bodies not being downloaded for use offline. Sometimes it would work, sometimes it wouldn't, and I couldn't detect a pattern.
- I did some more Googling and found an article called "Offline Folders" on Mozillazine. I used the Config Editor (Preferences/Advanced/General/Config Editor) to change two settings discussed in the article:
- I changed mail.imap.use_status_for_biff from true to false.
- I changed mail.server.default.autosync_offline_stores from false to true
According to the article this combination forces Thunderbird to download messages for offline use whenever you open it. - After I made that change it seemed like Thunderbird was downloading messages for use offline whenever I connected to the server, not just when I clicked the "work offline" icon. Also, sometimes when I went offline messages would still not yet be downloaded. So I set mai.server.default.autosync_offline_stores to false again.
- I noticed that mail.accountmanager.accounts somehow got account1 back, so I deleted account1 from that.
- I also noticed that server2 had offline_stores set to false, so I set it to true, even though server2 is no longer used.
Posted by AndyfromTucson at 11:45 0 comments
Labels: Thunderbird
2013-05-08
How to get directions from Google Maps into Gaia Maps for iOS so you can use them offline
I wanted a way to download directions from Google Maps onto an offline mapping program on the iPad so that I could use the iPad for navigation even when I don't have my cellular service. I have an iPad with 3G, but because I am a tightwad I only turn the 3G service on when I am on long trips. Also, we go plenty of places with little or no cell service out here in the west, so even if I wasn't a cheapskate I would want this capability.
It turns out that it is not that hard transfer directions from Google Maps into Gaia GPS as a route (not turn-by-turn directions, sorry) that you can view as a colored line on the map. These days my favorite iOS offline maps app is Gaia GPS. It can do offline street maps (Mapquest using Open Street Maps), satellite view, and topo maps.
- Sign in to Google on your computer browser, since you will need to work with the "My Maps" feature in Google Maps.
- Go to Google Maps and get directions to the place you want to go.
- At the bottom of the list of directions click the "Save to My Maps" link
- Select "Save to a new map" from the drop down that asks which map you want to save to.
- You will be taken to your new map in My Maps.
- Find a link called KML on the left sidebar, just under the title of your map, and click it.
- This will open a save file dialog for a KML file. Save it to your desktop.
- Now transfer the KML file from your computer to your iPad.
- One way to transfer the KML file to Gaia GPS is via email.
- Email the KML file to yourself.
- Open the Email on your iPad and open the attachment using Gaia GPS.
- Another way to transfer the file is via iTunes
- Plug your iPad into your computer
- Go to the tab for your iPad in iTunes and click the Apps button to get to a list of your apps
- Find Gaia GPS in the list of File Sharing apps
- Click the Add button at the bottom of the file list for Gaia GPS. This will open a dialog where you can select your KML file.
- After you have selected your KML file in iTunes, open Gaia GPS on your iPad. It should pop up a dialog saying there is a KML file waiting to be imported and asking you if you want to import it now. Do so.
- Once you have imported the KML into Gaia GPS it won't automatically show up on the map. You have to first tell Gaia GPS to display the route on the map.
- Go the the Saved screen in Gaia GPS
- On the Saved screen click the button on the top left for saved routes (it looks like two amoebas with stringy appendages)
- Your KML file should be listed at the top of the list of routes with an on/off switch next to it. Turn it on.
- Go back to the Map screen in Gaia GPS and your route will show up as a colored line.
Posted by AndyfromTucson at 10:04 0 comments
Labels: Gaia GPS, Google Maps, iOS, Maps
How to keep a Costco six pack of romaine hearts from going bad
The big drag with many Costco fruits and veggies is that unless you have a huge family or a restaurant you aren't going to use all of the big quantity Costco sells before it goes bad. I have, however, found a way to make the romaine hearts Costco sells in six packs last for weeks:
- Fill your sink with cold water and put the romaine hearts in to soak for about 30 minutes. This re-hydrates them.
- Let the romaine hearts dry for about 20-30 minutes after you soak them.
- Put each romaine heart in its own gallon sized zip loc bag, removing excess air before you seal, and then put them in the refrigerator.
- Every few days eyeball all of the bags and remove any leaves that are starting to brown. Typically the leaf on the bottom starts to brown after a few days, maybe because the weight of the romaine heart is resting on it.
Posted by AndyfromTucson at 09:56 0 comments
2013-03-14
How to escape from the View designer in MS SQL Server Management Studio (SSMS)
I started working with SQL Server, and MS SQL Server Management Studio about a year ago, and I quickly got frustrated with the View designer module. If you click on "New View" in the object explorer, or if you right click on an existing View and choose "Design," it opens up this multi-pane view designer with a graphical representation of the View on top, followed by some table listing the View elements, followed by the SQL for the view formatted as nearly impenetrable blocks of code. For simple Views the View designer was fine, but for complicated Views I came to hate working with it. I especially hated the fact that if I tried to format the SQL in a more readable layout, the View designer would throw out my formatting the next time I opened the View in Design mode.
I finally decided that there had to be a better way, and thanks to some discussions on Stack Exchange (natch) I pieced together the following:
- You can edit a View in plain SQL, and have your layout and formatting preserved when you save, by doing the following:
- Right click the View
- Select Tasks -> Script View as -> ALTER To -> New Query Editor Window
- Make your edits in the resulting Query Editor window
- Hit Execute when you are done to save your changes. The ALTER TO command replaces the current version of the View with your edited version.
- You can quickly clean up the brain dead SSMS formatting of the SQL of existing Views using the free poorsql.com website. You block and copy the ugly SQL into the window, choose from various formatting styles, and then the site instantly prepares a properly formatted version of the SQL.
Posted by AndyfromTucson at 09:45 1 comments
Labels: MS SQL Server, SQL, SSMS, T-SQL
2013-02-20
How to make an inexpensive magnetically mounted green laser pointer finder for your telescope
I wanted to start using a green laser pointer (GLP) as a supplement to my 9 x 50 finderscope on my Orion XT8 telescope, but I didn't want to spend a lot of money or time on it, and I didn't want to deal with drilling any holes in my optical tube assembly (OTA). I wanted the GLP finder because while the 9 x 50 finderscope is great for zeroing in on a faint fuzzy once you are in the right area, getting to the right area can be a pain with a Dobsonian.
I was able to find a very inexpensive (less than $10) green laser pointer on Amazon. There are more expensive varieties out there, but I figured that at such a low price it wouldn't be the end of the world if it didn't work well. As it turns out, the inexpensive GLP has worked fine for a while now.
But how to mount it on my Orion XT8 telescope? I didn't want to spend money on a real mount, and I didn't want to deal with drilling holes in my telescope (I know it's not really that big of a deal but I just wanted to avoid it if possible). Inspired by the way Apple uses magnets to secure things like the iPad cover, I looked on Amazon and ordered a package of 50 1/4" x 1/10" Neodymium rare earth magnets for less than $10.
When the magnets arrived I confronted the fact that I still didn't have a plan for exactly how connect them to the GLP. After mulling over a few possibilities that I rejected because they felt like too much work, I hit on the idea of simply taping four of the magnets to a popsicle stick using black electricians tape, a pair at each end, and then rubber-banding the GLP to the opposite side of the popsicle stick, like so:
Then it was time for a test drive. I was apprehensive about how hard it would be to align the GLP, but I quickly discovered that it was pretty easy. Just click the GLP on the tube, look through my 9 x 50 right angle correct image (RACI) finderscope, wiggle the shining laser beam back and forth until I see it in the finderscope, and then put the beam more or less close to the crosshairs. Using this method it takes literally only about 2 seconds to align the GLP. For vertical (for lack of a better word) alignment of the beam I just wedge stuff as needed between the GLP and the popsicle stick.
I quickly became addicted to using the GLP. It makes it a breeze to get the telescope pointed to within a degree or two of the target, and from there I use the RACI finderscope to hone in on it. No more contorting myself to get to the right spot behind a red dot finder, and seeing where a big green laser beam is pointed on the sky is a lot easier than correctly placing the red dot on an inexpensive red dot finder.
When winter came along I found another advantage to a magnetic GLP mount: it makes it easy to keep the GLP warm. I discovered that my GLP quickly dims when it gets cold, so to keep it usable I keep it in my pocket (or when it is really cold inside my pants against my skin) until I need to use it. Then I click it on the tube, quickly align the beam using the RACI finderscope, use the beam to put the telescope on the target, and then pop the GLP off and put it back in my pocket.
Posted by AndyfromTucson at 06:05 0 comments
Labels: Astronomy
2012-10-25
Recursively copy all PDF files from a directory tree to a single directory
Someone gave me a bunch of PDF files spread out through multiple subdirectories and I needed to get them all into a single directory.
In Mac OS X (and probably Linux) this will scan through the directory specified and its subdirectories and copy all of the PDF files to the target directory:
find /Users/joedokes/Desktop/source_directory -name "*.pdf" -exec cp {} /Users/joedokes/Desktop/target_directory \;
Posted by AndyfromTucson at 10:08 2 comments
2012-09-20
How to export a table as a SQL script using Microsoft SQL Server Management Studio
I come from the PHP-MySQL world, so I am used to being able to quickly generate a backup of a table as a SQL script (CREATE + INSERT) using the easy to find Export function in phpMyAdmin. When I had to use SQL Server for a project I was a bit puzzled when I couldn't find a similar feature in Microsoft SQL Server Management Studio (MS-SSMS). However, a bit of Googling revealed the (cumbersome) solution:
- In the Object Explorer in MS-SSMS right click the database that has the table you want to export.
- Select Tasks from the right-click menu.
- Select Generate Scripts from the sub menu, which will open a pop-up called Generate and Publish Scripts.
- Click Next on the Introduction screen, which takes you to the Choose Objects screen
- On the Choose Object screen select the "Select specific database objects" option
- Expand the Tables object by clicking the little plus sign
- Select the table(s) you want to export
- Click Next, which takes you to the Set Scripting Options screen.
- Choose where you want the output to go (file, clipboard or new query window)
- Click the Advanced button, which launches a pop-up window called "Advanced Scripting Options" with a list of options
- Scroll down to the "Types of data to script" option, which is at the very bottom of the set of options called "General."
- Change the "Types of data to script" option from "Schema only" to "Schema and data." This is what will make the SQL include the data from the table.
- Click OK to close the Advanced Scripting Options pop-up.
- Click Next on the Set Scripting Options screen.
- Click Next on the Summary screen where it says "Review your selections." This is what triggers the actual export of the table.
- Click Finish to close the Generate and Publish Scripts pop-up.
There, was that so bad? Well, yes, it was a lot of clicking for something that people probably do relatively frequently, but that is Microsoft for you.
Posted by AndyfromTucson at 07:53 0 comments
Labels: MS SQL Server, SQL, T-SQL
2012-06-18
How to simulate the MySQL group_concat function in MS SQL Server
The issue: I am writing a web app to track agreements where each agreement can have one, or multiple, account numbers associated with them, like so:
Agreement No. 1: Account Numbers = XYZ-123-123-123; XYZ-123-123-456; XYZ-123-123-789
Agreement No. 2: Account Numbers = XYZ-123-123-333
Agreement No. 3: Account Numbers = XYZ-123-123-123; XYZ-123-123-789
I quickly decided to store the account numbers in a separate table so that each agreement could have a variable number of account numbers associated with it:
Agreement_Account_Numbers table
Agreement_ID Account_Number
1 XYZ-123-123-123
1 XYZ-123-123-456
1 XYZ-123-123-789
2 XYZ-123-123-333
3 XYZ-123-123-123
3 XYZ-123-123-789
But then I ran into the problem of how to display all of an agreements account numbers in a table listing a number of agreements. I wanted an SQL query that would return one agreement per line, with all of the account numbers for each agreement concatenated in a single field. In MySQL this would be easy: do JOIN query with the agreements table linked by Agreement_ID to the on the agreement ID and then GROUP BY Agreement_ID and use the group_concat function to concatenate the Account_Number field. However, for this project I have to work with MS SQL Server and it apparently does not have any such function. Googling around led me to this excellent question on stackoverflow:
Simulating group_concat MySQL function in MS SQL Server 2005?
It
took me a while to sort out which answer to this question was easiest to implement, so I
am writing down what worked for me for my own future reference. Here is what I ended up with:
SELECT
Agreement_ID,
STUFF(
(SELECT '; ' + Account_Number
FROM agreement_account_numbers
WHERE agreement_id = a.agreement_id
FOR XML PATH (''))
, 1, 1, '') AS Account_Numbers
FROM Agreement_Account_Numbers AS a
GROUP BY agreement_id
The result of this query is:
Agreement_ID Account_Numbers
1 XYZ-123-123-123; XYZ-123-123-456; XYZ-123-123-789
2 XYZ-123-123-333
3 XYZ-123-123-123; XYZ-123-123-789
This query uses a sub-select clause to retrieve all of the account numbers for each agreement by linking the Agreement_Account_Numbers table back to itself (by giving the table the alias "a") and then putting sub-select results in a string using the MS SQL Server specific command FOR XML PATH (''). Then the STUFF function replaces the first character in the sub-select result string with a zero length string ('') to strip off the leading semi-colon that would otherwise be in front of the first account number.
The command is actually FOR XML with the PATH option specified, and then the tag to surround each row specified to be nothing (''). I tried figure out exactly now FOR XML works, and what the PATH option means, but as usual I found the MS documentation to be completely cryptic so I just accepted that it works.
Posted by AndyfromTucson at 09:28 4 comments
Labels: T-SQL, Transact SQL
2012-06-13
Always Google your problem first
If you have a problem that you don't know how to solve, or you need to do something you don't know how to do, the first thing you should always do is just google it. There are web pages and/or discussions describing how to do or fix just about everything these days, and a large part of the time you can get specific instructions from experts just be googling whatever it is you want to do.
For example, this morning I wanted to put a list of file names from a directory into a document. Instead of asking someone how to do it, or poking around and trying to figure out how to do it, I just googled "mac os x get copy list of file names to clipboard" and one of the top results was specific instructions on how to do just that.
Another example. The other day my spouse bought some fresh corn, and we wondered if you could microwave it instead of boiling it. We googled "microwave corn" and had specific instructions in seconds (it works great; I am never boiling another ear of corn).
This tactic works especially well for computer issues. If you get an error message, the first thing you should do is google it. The majority of the time you will have the solution in seconds.
You can stumble your way through a complex project that you have no idea how to do by using this tactic for each little step. I taught myself how to write web applications in PHP-MySQL this way.
Many people don't know this trick, so once you know it you can impress your friends and family as an expert on just about everything by using this tactic to instantly finding solutions for their problems.
Posted by AndyfromTucson at 07:29 0 comments
Labels: Basic Principles
2012-06-08
Don't get it until you really need it
The principle: Don't create or buy something until you know from actual practice exactly why you really need it.
This is also known as "You Aren't Gonna Need It"
When people are starting on some endeavor they often put significant effort or money into buying or making things that they think they will need. However, when it comes time to actually using these things it often turns out that you don't really need it after all, or it's not nearly as useful as you thought it would be, or you need something very different than what you thought you would need. And all the time, money and effort put into acquiring the thing turns out to be wasted.
On the other hand, if you wait until you know from experience that you actually need something, you can acquire exactly what you really need, and you will know how badly you really need it, which will give you a good idea how much time or money you should spend on it.
An example from hiking. I used to spend a lot on hiking boots because I thought I needed them because, by gosh, everyone else used them so they must be neccessary. Then I experimented with hiking in tennis shoes and sandals, and found that it was more comfortable, I got zero blisters for a change, I suffered fewer twisted ankles, and it was cheaper. I would have been much better off if I had started out hiking in just whatever shoes I had, and only purchased different shoes when and if I experienced actual problems.
Posted by AndyfromTucson at 07:45 0 comments
Labels: Basic Principles
2012-05-18
How to get MS SQL Server nvarchar() field to sort correctly using ORDER BY
I had an nvarchar field in MS SQL Server that wasn't sorting correctly when I did an ORDER BY on it. For example, 10 would be put before 9 if I sorted ASC. It turns out that MS SQL Server considers the position of each character in the field in sorting, and since the field is nvarchar (variable width) the digits of a number are not in consistent positions in the field. I found the solution in this post on stackoverflow.com:
Order By Clause for NVARCHAR column in SQL Server
The specific code is:
ORDER BY RIGHT(REPLICATE(N' ', 50) + the_column_you_want_to_sort_by, 50)
What this does is virtually add enough leading whitespaces to each entry to make the column look like a fixed width column for the purposes of the query.
Posted by AndyfromTucson at 04:59 0 comments
Labels: MS SQL Server, Transact SQL
2011-12-13
How to get a route from Google Maps on to an iPad so you can follow it offline
I wanted to find a way to download a route from Google Maps onto my iPad 3G so that I could follow the route on a map offline. I know that with the iPad 3G data plan turned on you can just use the Maps app to find and follow directions, but I am a frugalista and I like to keep the 3G data plan on my iPad turned off except when I am on long trips.
Here is the procedure I worked out, which requires that you own the $3.99 (as of Dec 2011) MotionX GPS HD app.
- Go to Google Maps and look up directions to the place you want to go.
- At the bottom of the directions click the Save to My Maps link.
- Go to Google My Places (fka My Maps) and select the map with directions you just saved.
- Click the KML link to download a KML file of the directions to your computer.
- Go to http://www.gpsvisualizer.com/ select the KML file to upload and pick GPS format for the output and click Go.
- Email the resulting GPX file to yourself.
- In Mail on your iPad open the email, tap the attachment, and select open in MotionX GPS HD app.
- This will open the MotionX GPS HD app where you can complete the import of the GPX track.
- This will just import the track into the MotionX GPS HD app. You need to separately download OpenStreetMaps for the relevant area in MotionX GPS HD in order to have the maps available offline.
Posted by AndyfromTucson at 07:51 0 comments
Labels: Google Maps, iOS, Maps
2011-11-10
How to manage iOS Newsstand subscriptions auto downloads
The screen where you manage automatic download settings for subscriptions in the new iOS Newsstand is hard to find (at least it was for me!) Here is how to get to it on your iPad, iPod Touch, or iPhone.
- Tap on the Settings app to get to the Settings screen
- Scroll down list of settings until you see the icon for the Store and tap that
- There will be a section of the Store settings called "Automatically download new content when on Wi-Fi" and all of your Newsstand subscriptions should be listed there with an on/off slider for each one.
Posted by AndyfromTucson at 05:39 0 comments
Labels: iOS, iOS Newsstand, iPad, iPhone, iPod Touch
2011-11-02
Save money using Google Voice plus a prepaid cellphone
A lot of prepaid mobile phone plans charge you only for the minutes you actually use, and if you don't use a lot of minutes each month it can save you a lot of money (I spend on average less than $10 a month on my T-Mobile prepaid service). If you get a Google Voice account, and set it up to ring not only your prepaid cell phone but also your home and office phones, then you can give everyone your Google Voice number as your mobile phone number, but answer calls to it on your house or work phone when you are not on the road.
Posted by AndyfromTucson at 05:05 0 comments
Labels: Frugality, Google Voice
2011-10-11
How to prevent sessions from expiring too quickly on PHP applications
A unique session ID is stored on a cookie on the users computer. When the user connects to the server the server looks for a file with that unique session ID in its temp folder, and if one exists it pulls variable values from that file. Every time any user connects to the server and starts a session the server generates a random number and then looks at some settings in php.ini to determine whether or not to clean out the temp folder. When it cleans out the temp folder it throws out session files older than the session.gc_maxlifetime setting in php.ini (set in seconds). In order to enable keeping users logged in for long periods I set session.gc_maxlifetime = 1814400 in the php.ini.
This works on MAMP installations also. Just edit to /Applications/MAMP/conf/php5.3/php.ini
Posted by AndyfromTucson at 15:58 0 comments