Automating ER/Studio with C# code.

I really enjoy data modelling and I really enjoy using the various modelling tools I’ve come across. All of them have their charms and their drawbacks. But I’ve yet to use one which works the way I want it to work out of the box. Anyway, at my current job I’m using ER/Studio Data Architect 9.7. It’s a fine tool.

But sometimes you need to move fast. Someone wants to see an ERD at a particular meeting and you haven’t made all the changes you need to make. So, you cut some corners. However, as in so many fields and disciplines, there are activities you can add to your work as you are going which cost you almost nothing, but which can be a big pain to go back and update at a later date.

In my current project, I was asked to change a bunch of attribute names in the logical model. No big deal right? Well, I had to push through this operation rather quickly. But then when I generated the physical model and then generated the physical database objects, I noticed that a lot of the column names didn’t match the attribute names in the logical model.

This is because ER/Studio allows you to enter an attribute name and give it a separate column name. This can be quite useful. You might have prefixes and abbreviations in your column names that you might want to hide from the subject matter experts who would be reviewing your logical model.

attribute_versus_column

But if you want those names to stay the same, and you change a whole bunch at once, it might cost you a lot of time to re-open all those dialogue boxes and update the default column names. Had you done it the first go-round, it would have only cost you a few seconds for each attribute. You could just copy and paste the changes you make in one text box into another. The biggest cost in terms of time is opening the entity then selecting the attribute and opening that dialogue box.

When it comes to grunt work like this, I tend to try to script out as much of the work as possible. When I worked with Sybase Power Designer I used Power Shell a lot. (You can see a sample of the work I did with that here and a more efficient version of the same script here.) But for some reason I couldn’t get the ER/Studio assemblies to load in PowerShell. So, I turned to C#.

I decided to post the code not because it’s great C# code,but sometimes when you’re playing around with something like ER/Studio automation, it’s good to have an example to work from – even if it’s not the most elegant example.

Below is my C# code to force the default column names to match the attribute names in an ER/Studio data model. (Don’t forget to add ER/Studio assemblies to your project!)

er_studio_ref

As always, this code is offered “AS-IS”. Please save your work, backup your files, etc, before you use it. Use it on a test version of your DM1 file and take all the usual precautions.


<pre style="font:inherit;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Data.OleDb;
using ERStudio;
using Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;


namespace er_studio_automation
{
    class er_studio_automator
    {
        private ERStudio.Application app;
        private ERStudio.SubModel smod;
        private ERStudio.Diagram diag;
        private ERStudio.Model mod;


        private void FixDefaultColumnNames()
        {
            ERStudio.Entity ent;
            foreach (ERStudio.EntityDisplay entD in smod.EntityDisplays())
            {
                ent = entD.ParentEntity();
                foreach (ERStudio.AttributeObj attr in ent.Attributes())
                {
                    //Console.WriteLine("attr " + attr.AttributeName + " -- " + attr.ColumnName);

                    if (String.Compare(attr.ColumnName, attr.AttributeName, false) != 0)
                    {
                        attr.ColumnName = attr.AttributeName;
                    }
                     
                }

            }
            diag.SaveFile("");

        }
        public er_studio_automator(string diagram_path, string model_name, string sub_model_name)
        {
            this.app = OpenApp();

            this.diag = OpenDiagram(diagram_path);
            this.mod = OpenModel(model_name);
            this.smod = OpenSubModel(sub_model_name);


        }

        static int Main(string[] args)
        {

            string diagram_path;
            string model_name;
            string sub_model_name;
            string action;
            string file_path;

            

            // Test if input arguments were supplied: 
            if (args.Length < 4)
            {
                System.Console.WriteLine("Please enter a \\-escaped diagram path, a model name and a submodel name");
                return 1;
            }

            diagram_path = args[0];
            model_name = args[1];
            sub_model_name = args[2];
            action = args[3];

            if (args.Length > 4)
            {
                file_path = args[4];
            }
            else
            {
                file_path = "";
            }

            er_studio_automator my_app = new er_studio_automator(diagram_path,model_name,sub_model_name);
            //my_app.OpenDiagram()
            switch (action)
            {

                case "fix_default_column_names":
                    my_app.FixDefaultColumnNames();
                    break;
 
                
                default:
                    System.Console.WriteLine("Command not recognized");
                    break;
            }

            //my_app.ValidateRelationships();
            
            my_app.CloseApp();
            return 0;

        }
        private void CloseApp()
        {
            //this.app.Quit();
            this.app.CloseDiagram(this.diag.FileName);
            this.app.Quit();
        }
        private ERStudio.Application OpenApp()
        {
            ERStudio.Application app = new ERStudio.Application();
            app.HideWindow();
            return app;

        }
        private ERStudio.Diagram OpenDiagram(string FileName) 
        {
            ERStudio.Diagram diag = app.OpenFile(FileName);
            return diag;
        }
        private ERStudio.Model OpenModel(string ModelName)
        {
            ERStudio.Model mod = diag.Models().Item[ModelName];
            return mod;
        }

        private ERStudio.SubModel OpenSubModel(string SubModelName)
        {
            
            
            ERStudio.SubModel smod = mod.SubModels().Item[SubModelName];
            return smod;
            
        }
        
    }
}
</pre>


This code assumes you’re running from the command-line. If you are running in debug mode from the Visual Studio IDE, you can put the appropriate command-line parameters in the project properties by right-clicking on the project in the solution explorer and selecting properties. The parameters are:

  1. Path to the DM1 file
  2. The model name
  3. The sub-model name
  4. A command. I’ve only put the code for one of my commands – the one that fixes the default attribute names – in this blog post. The command is fix_default_column_names.
  5. An optional file path. I use this with some other commands I’ve written which import Excel spreadsheets or spit them out.

Now, my model name is “Logical” and my sub model is called “Main Model”. My DM1 file is called data_warehouse_v1.DM1 and let’s say its path is G:\DW\data_warehouse_v1.DM1. Assuming your .exe file ends up in G:\DW\bin and is called automation.exe then the syntax to call this program from the command-line is:

G:\DW\bin\automation.exe G:\DW\data_warehouse_v1.DM1 “Logical” “Main Model” fix_default_column_names

You need to be sure that ER/Studio is not running when you execute this code! If ER/Studio is running when you execute this code, the code will crash and you’ll have an invisible instance of ER/Studio running on your machine. You can kill it through the task manager or through this PowerShell one-liner:


get-process | where-object {$_.Name -match "Erstudio"} | foreach-object {stop-process $_.Id}

Play around with it. Let me know what you think. If you can’t get it to work or have some ideas to make it better or just want to point something out, let me know.

So what are y’all automating these days?

Posted in Automation, Data Modeling, ER/Studio | Tagged , , , | Leave a comment

SQL Server install fails due to SQL Browser not starting

While trying to install SQL Server 2012 as a named instance I got the following error in the error log:

Exception type: Microsoft.SqlServer.Configuration.Sco.ScoException
Message:
Service ‘SQLBrowser’ start request failed.
HResult : 0x84bb0001
FacilityCode : 1211 (4bb)
ErrorCode : 1 (0001)
Data:
Feature = SQL_Browser_Redist_SqlBrowser_Cpu32
Timing = Startup
DisableRetry = true

After reading this article I suspected the problem might be due to a network activity monitor installed on the machine.

Uninstalling the activity monitor was not an option. However, SQL Browser is not needed if there is only a default instance running on the machine and since no other instances were running on the machine I decided to install SQL Server with one default instance.

This work-around allowed install to continue successfully. I may need to re-address this issue if I need to install a second instance of SQL Server on this machine.

Posted in DBA, Frustrating errors, SQL, SQL Server 2012 | Tagged , , , , , | Leave a comment

Broaden your vision

Where there is no vision, the people perish
(Proverbs 29:18A, KJV)

It’s old wisdom but still valid. When you have no direction you flounder and sometimes the people around you flounder, too. This is true in the tech world as much as it is in more obviously social arenas.

A corollary of this is that if your vision is a bad one then the people may just barely scrape by.

A while back I posted some code that imported documentation from a CSV file and used that data to update a Sybase PowerDesigner data model. I mentioned that the code was slow because you were potentially iterating through almost the entire data model for each piece of column documentation you imported. I was pretty sure there was some method of the PowerDesigner COM object that held the key to fixing my performance problem. This may have been true but I managed to solve it by changing my vision. I moved from a very limited vision to a broader vision and this fixed things.

I was pretty interested in learning a lot about the PowerDesigner COM object. I was more interested in this than in solving my problem – e.g., importing documentation into the data model. I so focused on getting the PowerDesigner COM object to do interesting things that I didn’t pay much attention to the less nifty parts of my project – the lowly, old CSV file.

Iterating through a PowerDesigner data model through the COM interface is slow but interesting. Pulling a CSV file into an in-memory hash object and searching the hash object is less interesting. But it allowed me to solve the problem significantly faster. On my machine, when the CSV file is the pulled into an in-memory hash object and the PowerDesigner data model is iterated over only once the code executes in almost 1/10th the time it takes to iterate over the PowerDesigner data model multiple times and the CSV file only once.

Once I stepped back and looked at things more objectively it was easy to see how to make this thing run faster. Once my vision became broader – e.g., solving the problem rather than solving the problem by getting PowerDesigner to do something interesting – I was able to see the obvious solution.

The root of the problem was that my vision was too specific.

This seems to happen a lot in the tech world. XML is a great answer to a lot of different problems but a number of years ago people were using it to solve all sorts of problems to which it wasn’t suited. It seemed almost as if there was an unwritten mandate in a number of organizations that if you couldn’t fit XML into your application then you wouldn’t get your project funded. Developers were trying like mad to get that acronym on to their resumes, too, and that didn’t help. A lot of people got soured on XML or believed it was all hype because of that. The dust has settled and XML is a mature technology with a variety of uses but it was hurt by the narrowing of vision that came along with the XML boom.

Anyway, I’ll post the updated code below. It has two functions which do the same work. One of them does it by iterating over the PowerDesigner data model one time and finding the appropriate CSV data in an in-memory hash object. That function is called test_hash. There is another function called test_model_iteration that basically uses the algorithm in the original post. I’ve also included some helper functions that are used by test_model_iteration. The script outputs the start time and end time of each call so you can see for yourself that the in-memory hash approach is much faster.

As in the original example, the following variables need to be set:

$pathToDocumentation is a path to the CSV file with a column called Column and a column called Description

$PathToModel is a path to the Sybase PowerDesigner model

$tableToUpdate is the name of the table whose documentation comments you are updating.

Does anyone else have any stories about how the narrowness or broadness of their vision affected their work?

Please let me know if you have any questions about the code or have problems adapting it to your situation. I can’t promise I’ll have time to help you but I might be able to offer a comment or two.


Function GetTable($Model,$table){

$Model.Children | where-object{$_.Name -eq $table}

}

Function GetColumn ($Model,$table, $column){

GetTable -Model $Model -table $table | foreach-object{$_.Columns} | where-object{$_.Name -eq $column}

}

Function GetColumnComment($Model,$table, $column){

GetTable -Model $Model -table $table | GetColumn -Model $Model -Table $table -Column $column | foreach-object{$_.Comment}

}

Function SetColumnComment($Model,$table, $column, $comment){

GetTable -Model $Model -table $table | GetColumn -Model $Model -Table $table -Column $column | foreach-object{

$_.Comment = $comment

}

}

function test_hash{

foreach ($row in $documentaion_raw){

$documentaion[$row.Column] = $row.Description

}

$MyModel.Children | foreach-object{

If ($_.ClassName -eq "Table" -and $_.Name -eq $tableToUpdate){

$_.Columns | foreach-object{

$_.Comment = $documentaion[$_.Name]

}

}

}

}

function test_model_iteration{

Foreach($comment_entry in $documentaion_raw){

SetColumnComment -Model $MyModel -table $tableToUpdate -column $comment_entry.Column -comment $comment_entry.Description

}

}

$pathToDocumentation = "C:\Documents and Settings\My Documents\PD_Test_Project\data models\documentation\test_import.csv"

$PathToModel = "C:\Documents and Settings\My Documents\PD_Test_Project\data models\PD_Test_Project.pdm"
$tableToUpdate = "ps_import_test"

$PDApp = new-object -comobject PowerDesigner.Application

$MyModel = $PDApp.OpenModel($PathToModel)

$documentaion_raw = Import-Csv($pathToDocumentation)

$documentaion = @{}

Get-Date

test_hash

Get-Date

Get-Date

test_model_iteration

Get-Date

$MyModel.Save()

$MyModel.Close()

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($PDApp) > $null

Remove-Variable MyModel

Remove-Variable PDApp

Posted in Automation, Business, Data Modeling, Life, PowerShell, spirit, Sybase PowerDesigner, Tools | Tagged , , , | 2 Comments

Data Modeling, Conciseness and Philosophy

Graeme Simsion and Graham Witt use the term conciseness to describe one of the most interesting aspects of a data model. Simsion and Witt write that a good data model

implicitly defines a whole set of screens, reports and processes needed to capture, update, retrieve and delete the specified data.

The data modeling process can similarly take us more directly to the heart of the business requirements

When I first read this quote it was like a light going off in my head. I always felt that a good understanding of the data model was 90% of the battle to understanding an application, a business process or even possibly an enterprise.

On reflection, this really shouldn’t be much of a surprise. I think at our heart we are conceptual beings more than task oriented beings. We are often finding new and supposedly better ways of doing things but basically we are still living in a world of people, places and things and the relationships between them. Email, Facebook and Twitter may have changed the way we meet, keep up with and relate to people but it’s still essentially about relationships.

Get the concepts right. The code will follow.

If this sounds a bit on the philosophical side, I suppose that can be forgiven as apparently I’m not the only one who sees data modeling as being a primarily conceptual activity. With this article I also had that feeling of everything falling into place. People have sometimes asked me if my philosophy training was useful and I would say that it really did seem to have a positive impact on my career as a database professional but I never really had the time to sit down and think about why this was.

Posted in Data Modeling, Life, Uncategorized | Tagged , , | Leave a comment

Importing Column Documentation from a CSV into a Sybase PowerDesigner Data Model

(Update – I have a more efficient version of this script posted here)
I’m a big fan of data modeling tools. I used to chafe against them as so often it was easier for me to think in code. But the advantages of using tools like E/R Studio, Toad Data Modeler and Sybase PowerDesigner became apparent quickly. Being able to visually look at your data model through diagrams and automatically generated reports allowed you to get a general sense of what was going on in the database as a whole. And of course, it was much easier to document the database through the tool as you created or modified your tables with the same tool. And many of these tools have built in checks and warnings that can be very useful.

Still, certain repetitive tasks are easier to do through scripts. Or even through scripts generated by scripts. Right now I’m working with PowerDesigner and it has some built in scripting capabilities but there were some aspects of it that I just couldn’t get used to. And I already knew PowerShell pretty well so I decided to try and see if I could use PowerShell to do some grunt work.

Here’s the scenario. A non-technical subject area expert is asked to review the documentation of one of the key entities in your model. You are asked to give them a spreadsheet with all the attributes/columns as well as the description of each columns. The subject area expert makes some improvements in the spreadsheet and sends it back.

Now you need to import the spreadsheet and update the data model with the revised documentation.

For the sake of this example, we’ll assume that you want to store the column-level documentation in the Comment field of the column. You might want to put it in the annotations or somewhere else depending on your situation.

$PathToModel holds the path to the data model file.

$pathToDocumentation is the path to the CSV file you are importing. It should have a column called Column which has the column names and Description which has the new comment you want in the data model.

$tableToUpdate should have the name of the table in the model you want to update.

Obviously, this isn’t a production utility. It’s just a quick and dirty script to give you ideas for building more useful, flexible tools. I will probably use this as a basis for a PowerDesigner library if I end up doing a lot of PowerDesigner work.

Here is the code:


Function GetComment($table, $column){

$MyModel.Children | where-object{$_.Name -eq $table} | foreach-object{$_.Columns} | where-object{$_.Name -eq $column} | foreach-object{$_.Comment}

}

Function SetComment($table, $column, $comment){

$MyModel.Children | where-object{$_.Name -eq $table} | foreach-object{$_.Columns} | where-object{$_.Name -eq $column} | foreach-object{

$_.Comment = $comment

}

}

$PathToModel = "C:\my_model.pdm"

$pathToDocumentation = "C:\updated_documentation.csv"

$PDApp = new-object -comobject PowerDesigner.Application

$tableToUpdate = "ps_import_test"

$MyModel = $PDApp.OpenModel($PathToModel)

$documentaion = Import-Csv($pathToDocumentation)

Foreach($comment_entry in $documentaion){

SetComment -table $tableToUpdate -column $comment_entry.Column -comment $comment_entry.Description

}

$MyModel.Save()

$MyModel.Close()

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($PDApp)

Remove-Variable PDApp

The big problem with this code is that for each update you may end up iterating over the whole model, so it might be slow for large models. It looks like there are methods in the COM interface that might avoid this but I had no luck calling them from PowerShell. Anyone know the PowerDesigner object model well enough to help with this?

Anyone else have some good automation tips you’d like to share?

Posted in Automation, Data Modeling, PowerShell, Sybase PowerDesigner, Tools | 4 Comments

SSRS report throws an error that says a parameter doesn’t exist when the report designer clearly shows the parameter exists

The order in which the parameters appear in the BIDS Report Data tab can be the difference between your report executing and it failing. Failure to pay attention to this will give you very mysterious error messages!

"The Value expression for the query parameter PARAMNAME contains and error:The expression that references the parameter PARAMNAME does not exist in the parameters collection. Letters in the names of parameters must have the correct case"

It may be visible at design time but not come into scope when the particular expression is evaluated!

You can force the order of the parameters by going into the XML code and adjusting as needed.

Posted in Frustrating errors, SQL | Tagged , , | 8 Comments

Downloading the Results of a Twitter Search using PowerShell and SQL (part 3)

Part one of this series is here and part two is here. You’ll need the SQL scripts from part two in order for the code below to work but you can skip part one unless you’re curious to see the evolution of this project.

First off, I found a bug in my code. A unique contraint violation may be thrown if the exact same tweet is tweeted at the exact same time by two different users. I didn’t code to handle this because I thought it was an incredibly unlikely scenario but given the popularity of automatic tweeting – eg, “Share this on Twitter” buttons – it seems like it is a scenario which can and does happen.

Anyway, I decided to create a different constraint. Here is the code to drop the old one and add the new one.


use twitter
go

/*
a web app which auto tweets for a user 
might cause two identical tweets 
at the same second
*/

if exists (select 1 from sys.indexes where name = N'uq_tblTweet_tweet_tweetDate')
	alter table tblTweet drop constraint uq_tblTweet_tweet_tweetDate

alter table tblTweet
add constraint uq_tblTweet_tweet_tweetDate_twitterUserId unique (tweet, tweetDate, twitterUserId) 


Secondly, I added some paramters to the script. The parameter -searchString takes a single string to search on. Or you can specify a file path as an argument to the -inputFile parameter and it will go through each of the strings and do a search on those strings.

If you use both parameters it will do the -searchString first and then the -inputFile

I needed to update the proc which moves data from the staging table to the data tables so that the staging table doesn’t grow indefinitely. I like the data to hang around for a bit in case I need to debug some error so I don’t want to truncate the table every day. I decided to add a paramater to the proc so that it deletes data whose import date (not the twitter date but the date the data was imported) is more than a certain number of days old. The number of days is passed as an argument on the command line of the PowerShell script call. The default is 30 days for both the PowerShell script and the stored proc and the paramter is named -delAgedStagingData. If you pass a 0 it will not delete any data

Here is the updated proc:


use twitter
go

if object_id(N'uspLoadTwitterDataFromStaging') is not null
	drop procedure uspLoadTwitterDataFromStaging

go

create procedure uspLoadTwitterDataFromStaging
/*
If data is oldet than @deleteDataAge in days, delete it
default = 30
if 0 then don't delete data
*/
@delAgedStagingData int = 30 
as
begin


	insert into tblTwitterUser (twitterUserName)
	select twitterUser
	from tblTwitterStaging
	except
	select twitterUserName
	from tblTwitterUser


	/*
	I could prime this table in a config step 
	but I want the whole thing to be driven by user configurable files in the end product
	or parameters on the command line

	Anyway, the PowerShell script is responsible for inserting the search string into the staging table
	*/

	insert into tblSearchString (searchString)
	select searchString
	from tblTwitterStaging
	except 
	select searchString
	from tblSearchString


	--there is some weird date stuff going on - salvage what you can!
	update tblTwitterStaging
	set twitterdate = convert(datetime,left(twitterdate,10))
	where isdate(twitterdate) = 0


	insert into tblTweet(tweet,tweetDate,twitterUserId)
	select distinct stg.tweet, convert(datetime,stg.twitterDate), u.twitterUserId
	from tblTwitterStaging stg
	inner join tblTwitterUSer u
	on stg.twitterUser = u.twitterUserName

	except select tweet,tweetDate,twitterUserId
	from tblTweet


	insert into tblTweetBySearchString(tweetId,searchStringId)
	select t.tweetId, s.searchStringId
	from tblTwitterStaging stg
	inner join tblTweet t
	on stg.tweet = t.tweet
	inner join tblSearchString s
	on stg.searchString = s.searchString
	except select tweetId,searchStringId
	from tblTweetBySearchString





	if @delAgedStagingData <> 0
		
		delete tblTwitterStaging where datediff(day,importDate,getdate()) > @delAgedStagingData
	
		
end

I also found one case where the published string came back with a format that SQL server couldn’t handle. If I dropped off the time then it could convert. That causes a bit of data loss but I figure it’s better than losing the record and it seems like the situation is pretty rare.

Thirdly, I decided for ease of use to do the URL encoding in the PowerShell script. So when you pass in a string you simply type the search string as you would into any search box. So, if you want to search for “i am the cloud” you can just pass that string as a paramter.

Here is the updated PowerShell script.



param([string]$searchString = "", [string]$inputFile = "", [int]$delAgedStagingData = 30)
Write-Host "searchString: $searchString"
Write-Host "inputFile: $inputFile"
Write-Host "delAgedStagingData: $delAgedStagingData"


[System.Reflection.Assembly]::LoadWithPartialName("System.Web") | out-null
$searchString = [System.Web.HttpUtility]::UrlEncode($searchString)



Function getSearchPage ($searchString, $page)
{
	"searchString = $searchString"
	"page = $page"


	$req = "http://search.twitter.com/search.atom?q=$searchString&show_user=1&rpp=100&since_id=1&page=$page"
	
	
	"`$req = $req"
	
	([xml](new-object net.webclient).DownloadString($req)).feed.entry |
	%{

		#replace problematic characters in input
		$title = $_.title -replace ("`t","``t")
		$title = $title -replace ("'","''")
		$title = $title -replace ("`n","``n")
		$title = $title -replace ("`r","``r")
		$title = $title -replace ("`$","``$")
		$title = $title -replace ("`"","`"`"")
		$published = $_.published -replace ("`t"," ")
		$published = $published -replace ("'","''")
		$published = $published -replace ("`n","``n")
		$published = $published -replace ("`"","`"`"")
		
		
		
		
		$splitData = $title.split(":")
		$twitterUser = $splitData[0]
		
		$tweet = $title.substring($twitterUser.length,$title.length - $twitterUser.length)
		if ($tweet.length -ge 2)
		{$tweet = $tweet.substring(2,$tweet.length -2)}
		
		

		
		#turn input into sql statement
		if ($tweet.length -gt 0){
			$sql = "insert into twitter.dbo.tblTwitterStaging 
			(twitterUser,tweet, twitterDate,searchString) 
			select '$twitterUser','$tweet' ,'$published','$searchString'" 
			
			sqlcmd -E -Q $sql 
			

		}

	} 

	
}

Function getLast10SearchPages ($searchString)
{
	for ($i=10; $i -ge 1; $i--)
	{



		$i

		getSearchPage $searchString $i



	} 
}


#process command line searhc string first
if ($searchString -ne '') {getLast10SearchPages ($searchString)}

#process any search strings in the file
if ($inputFile  -ne '') {Get-Content $inputFile | Foreach-Object {getLast10SearchPages ([System.Web.HttpUtility]::UrlEncode($_))}}



sqlcmd -E -Q "exec twitter.dbo.uspLoadTwitterDataFromStaging @delAgedStagingData = $delAgedStagingData"



I’ve been calling the file twitter_search_to_db.ps1 and assuming that you call yours the same thing here are some sample calls. I created a text file called search_strings.txt which sits in the same directory in which I’m running my script. Here is what is saved in search_strings.txt:

#powershell
#sqlhelp
i am the cloud
death cab for cutie
florence + the machine
mary timony
Jolie Holland

Here is the call with a search string:

.\twitter_search_to_db.ps1 -searchString "J. Vernon McGee"

Here is a call with a file parameter:

.\twitter_search_to_db.ps1 -inputFile ".\search_strings.txt" -delAgedStagingData 30

And here is a call with both:

.\twitter_search_to_db.ps1 -searchString "J. Vernon McGee" -inputFile ".\search_strings.txt" 

Notice that the search string is stored URL encoded in the tables:

select * from twitter.dbo.tblSearchString

I figure that this is closer to what is actually required by the program. It should be fairly safe for use in SQL and over the web. It’s up to the interface to transform user input into something computer friendly. You could store both inside but I try to avoid repetivive data and since the unencoded data should be fairly easy to get from the encoded data it seems silly to have both. You might end up with difficult to find bugs if you have both.

I would recommend you add this as a scheduled task. That’s fairly easy to do. You can find details on that here along with some other nice PowerShell tricks.

I hope to play around a bit with displaying the results but my plan for my next post is probably going to be some pure T-SQL stuff. I feel like I could go on and on with this project. I love PowerShell but my deeper interest in T-SQL is starting to pull me away. So I’m going to take a brief PowerShell vaction.

Posted in PowerShell, SQL | Tagged , , , , , , | Leave a comment