Monday, January 28, 2013

deploy Internet Radio

Internet Radio Advantages

  • Internet Radio is static free, high fidelity
  • Internet Radio can be high bandwidth, rich stereo thru your current amplifier.
  • Virtually every "traditional, over the air" radio station has a parallel internet stream
  • There are 10s of thousands of internet streams, not broadcast "traditional, over the air"

To deploy the internet radio, I used Amazon.com to

  • search on: ' hi fi internet radio '
  • look at internet radio component abilities vs. my amplifier/surround sound system abilities:
  • purchase this internet radio :

o Grace Digital GDI-IRD4500m High Performance Stereo Internet Radio - Black by Grace Digital

You will read internet radio instructions to figure out how to

· connect your internet radio to your amplifier/surround sound system

o e.g. in an empty slot next to your, e.g., CD Player

· connect your internet radio to the internet

o with a cable

o or wirelessly

· use a web page to configure your radio stations and "URL Streams"

o Suggestions / "Works for me" procedures:

§ Use Google Chrome Browser - to search and create Radio Stations and " Windows Media URL Streams"

§ Use Internet Explorer - to launch and test Radio Stations and URL Streams in your Windows Media Browser Media Player

· use internet radio remote control to select & listen to Radio Stations and URL Streams 

Your internet Radio will have thousands of built in radio stations

Here are some "URL Streams" that you can add to your " internet radio - My Streams"

Q2 - Modern Classical - http://wqxr-q2.streamguys.com/q2.m3u

WRTI - Philadelphia - Classical Stream - http://www.publicbroadcasting.net/wrti/ppr/wrti.m3u

Space SOMA Drone http://somafm.com/wma128/dronezone.asx

  • SOMA is awesome for taking a Nap!

Friday, August 17, 2012

GridView to Excel - prevents RegisterForEventValidation can only be called during Render();

GridView to Excel - prevents 

"RegisterForEventValidation can only be called during Render()"


'---------------------------------------------------------

'aspx

'---------------------------------------------------------

<%@ Page Language="vb" AutoEventWireup="true" enableEventValidation ="false" CodeBehind="AssayList.aspx.vb" Inherits="TestRequest.AssayList" %>

  

'---------------------------------------------------------

'aspx.vb

'---------------------------------------------------------

 Protected Sub ibExcelExport_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ibExcelExport.Click

        ExportToExcel("MyReport.xls", Me.gv1)

    End Sub

   

Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)

 

    End Sub

   

Public Sub ExportToExcel(ByVal strFileName As String, ByVal dg As GridView)

        Response.Clear()

        Response.Buffer = True

        Response.ContentType = "application/vnd.ms-excel"

        Response.Charset = ""

        Me.EnableViewState = False

        Dim oStringWriter As New System.IO.StringWriter

        Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)

 

        dg.RenderControl(oHtmlTextWriter)

 

        Response.Write(oStringWriter.ToString())

        Response.[End]()

 

    End Sub

Monday, June 25, 2012

Tutorials - Getting Started

Friday, March 2, 2012

Get index of an enum via string

Get index of an enum via string

Thanks to by serkan sendur : http://www.daniweb.com/software-development/csharp/code/217261

I have a bunch of checkboxes on a Windows form  

and I put the exact checkbox names in an enum chkSelectedenum

I want to collect the checkbox names into a hashset

I will pass the hashset to another class that also can see chkSelectedenum

So that

1.       we do not have to hardcode checkbox names into if..then.else..switch statements

2.       another class can work with the hashset & enum

       enum chkSelectedenum

        {

            Chk1,

            Chk2,

            Chk3

        }

        private void btn_Click(object sender, EventArgs e)

        {

            try

            {

                HashSet<string> hashSet_Checked = new HashSet<string>();

                foreach(Control c in this.Controls)

                {   

                    if(c is CheckBox)   

                    {

                        CheckBox chk = (CheckBox)c;

                        if (chk.Checked)

                       

                            hashSet_Checked.Add(chk.Name);

                        }

                    }

                }

 

//another class can work with the hashset & enum

                foreach (string chkName in hashSet_Checked)

                {

                    chkSelectedenum flag = (chkSelectedenum)Enum.Parse(typeof(chkSelectedenum), chkName);

                    Debug.WriteLine(flag.ToString());

                }

 

            }

            catch (Exception ex)

            {

 

            }

        }

 

 

 

 

 

Tuesday, January 31, 2012

ASP.NET MVC 3 Walkthroughs & Books

ASP.NET MVC 3 Walkthroughs & Books

1.    Intro to ASP.NET MVC 3 - Rick Anderson

http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/getting-started-with-mvc3-part1-cs

2.    Building an MVC 3 App with Database First – Julie Lerman

a.     http://msdn.microsoft.com/en-us/data/gg685489

3.    Walkthrough: Retrieving Entity Types with a Stored Procedure (Entity Data Model Tools

a.     http://msdn.microsoft.com/en-us/library/cc716672.aspx

4.    Book – Wrox - Professional ASP.NET MVC 3

http://www.wrox.com/WileyCDA/WroxTitle/Professional-ASP-NET-MVC-3.productCd-1118076583,descCd-DOWNLOAD.html

Last n Months Display-Value Pair for DropDown List greater than a minimumm date

Create PROCEDURE [dbo].[ts_Dates]

@isTo bit

AS

 

/*

-----------------------------------------------------

--Last Dates Display-Value Pair for DropDown List

for date greater than

-----------------------------------------------------

exec [dbo].[ts_Dates] 0

exec [dbo].[ts_Dates] 1

*/

 

declare @minToDate datetime

declare @minFromDate datetime

select @minToDate = min(<date>) from <table>;

select @minFromDate = DATEADD(MONTH,-1,min(<date>)) from <table>;

--print @minToDate

--print @minFromDate

 

 

if @isTo = 1

       begin

              --Display                                   Value

              ------------------------------------------- --------------

              --February 29, 2012                         2/29/2012

              --January 31, 2012                          1/31/2012

              --December 31, 2011                         12/31/2011

 

        --with

              WITH R(N) AS (

              sELECT 0

              UNION ALL

              SELECT N+1  FROM R

              WHERE N < 100 )

              , cte2 (Display, Value, [date]) as (

              SELECT DATENAME(MONTH,DATEADD(MONTH,-N,GETDATE()))

              + ' ' + CONVERT(VARCHAR(4),DATEPART(Day, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,DATEADD(MONTH,-N,GETDATE()))+1,0))))

              + ', ' + CAST(DATEPART(YEAR,DATEADD(MONTH,-N,GETDATE())) AS VARCHAR(4)) AS Display

              , CONVERT(VARCHAR(4),DATEPART(MONTH,DATEADD(MONTH,-N,GETDATE())))

               + '/'

               + CONVERT(VARCHAR(4),DATEPART(Day, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,DATEADD(MONTH,-N,GETDATE()))+1,0))))

               +'/' + CONVERT(VARCHAR(4),DATEPART(YEAR,DATEADD(MONTH,-N,GETDATE()))) AS [Value]

              , DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,DATEADD(MONTH,-N,GETDATE()))+1,0)) as [date]

              FROM R )

              select * from cte2 where [date] > @minToDate

       end

else

       begin

              --Display                                Value

              ---------------------------------------- -----------

              --February 1, 2012                       2/1/2012

              --January 1, 2012                        1/1/2012

              --December 1, 2011                       12/1/2011

              WITH R(N) AS (

              sELECT 0

              UNION ALL

              SELECT N+1  FROM R

              WHERE N < 100 )

              , cte2 (Display, Value, [date]) as (

              SELECT DATENAME(MONTH,DATEADD(MONTH,-N,GETDATE())) + ' 1, ' +

                CAST(DATEPART(YEAR,DATEADD(MONTH,-N,GETDATE())) AS VARCHAR(4)) AS Display

              , CONVERT(VARCHAR(4),DATEPART(MONTH,DATEADD(MONTH,-N,GETDATE())))

               + '/1/' + CONVERT(VARCHAR(4),DATEPART(YEAR,DATEADD(MONTH,-N,GETDATE()))) AS [Value]

               , DATEADD(MONTH, DATEDIFF(MONTH, 0, DATEADD(MONTH,-N,GETDATE())), 0) as [date]

              FROM R )

              select * from cte2 where [date] > @minFromDate

  end

Create

PROCEDURE [dbo].[ts_Dates]

@isTo bit

AS

 

/*

-----------------------------------------------------

--Last 100 Months Display-Value Pair for DropDown List

-----------------------------------------------------

exec [dbo].[ts_Dates] 0

exec [dbo].[ts_Dates] 1

*/

 

if @isTo = 1

       begin

              --Display                                   Value

              ------------------------------------------- --------------

              --February 29, 2012                         2/29/2012

              --January 31, 2012                          1/31/2012

              --December 31, 2011                         12/31/2011

 

              WITH R(N) AS (

              sELECT 0

              UNION ALL

              SELECT N+1  FROM R

              WHERE N < 100 )

              SELECT DATENAME(MONTH,DATEADD(MONTH,-N,GETDATE()))

              + ' ' + CONVERT(VARCHAR(4),DATEPART(Day, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,DATEADD(MONTH,-N,GETDATE()))+1,0))))

              + ', ' + CAST(DATEPART(YEAR,DATEADD(MONTH,-N,GETDATE())) AS VARCHAR(4)) AS Display

              , CONVERT(VARCHAR(4),DATEPART(MONTH,DATEADD(MONTH,-N,GETDATE())))

               + '/'

               + CONVERT(VARCHAR(4),DATEPART(Day, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,DATEADD(MONTH,-N,GETDATE()))+1,0))))

               +'/' + CONVERT(VARCHAR(4),DATEPART(YEAR,DATEADD(MONTH,-N,GETDATE()))) 

               AS [Value]

              FROM R

       end

else

       begin

              --Display                                Value

              ---------------------------------------- -----------

              --February 1, 2012                       2/1/2012

              --January 1, 2012                        1/1/2012

              --December 1, 2011                       12/1/2011

              WITH R(N) AS (

              sELECT 0

              UNION ALL

              SELECT N+1  FROM R

              WHERE N < 100 )

              SELECT DATENAME(MONTH,DATEADD(MONTH,-N,GETDATE())) + ' 1, ' +

                CAST(DATEPART(YEAR,DATEADD(MONTH,-N,GETDATE())) AS VARCHAR(4)) AS Display

              , CONVERT(VARCHAR(4),DATEPART(MONTH,DATEADD(MONTH,-N,GETDATE())))

               + '/1/' + CONVERT(VARCHAR(4),DATEPART(YEAR,DATEADD(MONTH,-N,GETDATE()))) 

               AS [Value]

              FROM R

       end

 

CREATE

FUNCTION [dbo].[tsDatesInRange] (@DateStart DATETIME, @DateEnd DATETIME) RETURNS TABLE AS RETURN (

--=======================================================================================

-- Find first of every month between the start and end dates (inclusive)

--=======================================================================================

--===== Here are the two parameters you wanted

/*

DECLARE @DateStart DATETIME

DECLARE @DateEnd DATETIME

SELECT @DateStart = '20070429',

@DateEnd = '20081201'

select * from tsDatesInRange('20070429', '20081201')

*/

--===== Find the dates using a Tally table as a counter.

-- The outer select formats it. Once cached, it's incredibly fast.

WITH

cteTally

AS

(

--==== Returns a value of 1 to the number of months in date range

SELECT TOP (DATEDIFF(mm,

DATEADD(mm,DATEDIFF(mm,0,@DateStart),0), --First of start month

DATEADD(mm,DATEDIFF(mm,0,@DateEnd)+1,0))) --First of month after end month

N

= ROW_NUMBER() OVER (ORDER BY t1.Object_ID)

FROM Master.sys.All_Columns t1

CROSS JOIN Master.sys.All_Columns t2

)

SELECT N,

--DateStart = DATEADD(mm,DATEDIFF(mm,0,@DateStart)+t.N-1,0),

--NextStart = DATEADD(mm,DATEDIFF(mm,0,@DateStart)+t.N,0)

month(DATEADD(mm,DATEDIFF(mm,0,@DateStart)+t.N-1,0)) [Month]

,Year(DATEADD(mm,DATEDIFF(mm,0,@DateStart)+t.N-1,0)) [Year]

FROM cteTally t

)

GO

Thursday, January 12, 2012

Generate insert SQL for a table

Thanks to

Andraax
Aged Yak Warrior

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=23133

 

Generate insert SQL for a table - Insert this stored proc:

 

create

proc [dbo].[generate_inserts] @table varchar(50)

--Generate inserts for table @table

AS

declare

@cols varchar(1000)

declare

@col varchar(50)

/*

generate_inserts 'PlanLevel1ControlResponsibility'

*/

set

@cols=''

declare

colcur

cursor

for

select

column_name

from

information_schema.columns

where

table_name=@table

open

colcur

fetch

next from colcur into @col

while

@@fetch_status=0

begin

select

@cols = @cols + ', ' + @col

fetch

next from colcur into @col

end

close

colcur

deallocate

colcur

select

@cols = substring(@cols, 3, datalength(@cols))

--select @cols

declare

@sql varchar(4000)

declare

@colname varchar(100),

@coltype

varchar(30)

select

@sql = 'select replace(''insert ' + @table + ' (' + @cols + ') '

select

@sql = @sql + 'values ('''

declare

ccur

cursor

for

select

column_name, data_type

from

information_schema.columns

where

table_name=@table

open

ccur

fetch

from ccur into @colname, @coltype

while

@@fetch_status=0

begin

if

@coltype in ('varchar', 'char', 'datetime')

select

@sql=@sql + ''''''

select

@sql=@sql + ' + coalesce(convert(varchar, ' + @colname + '), ''null'') + '

if

@coltype in ('varchar', 'char', 'datetime')

select

@sql=@sql + ''''''

select

@sql = @sql + ''', '''

fetch

from ccur into @colname, @coltype

end

close

ccur

deallocate

ccur

select

@sql=substring(@sql, 1, datalength(@sql)-3)

select

@sql=@sql + ')'', ''''''null'''''', ''null'') from ' + @table

exec

(@sql)

GO

 

 

 

 

Sunday, January 8, 2012

list schema, table, row count in a database

-----------------------------------------------------------

--all info from Tables

-----------------------------------------------------------

SELECT

*

FROM

sys.Tables

-----------------------------------------------------------

--Schema.name from Tables

-----------------------------------------------------------

SELECT

'['+SCHEMA_NAME(schema_id)+'].['+name+']'

AS

SchemaTable

FROM

sys.tables

-----------------------------------------------------------

--Schema, name from Tables

-----------------------------------------------------------

SELECT

SCHEMA_NAME(schema_id) [Schema]

,

name [Table]

FROM

sys.tables

-----------------------------------------------------------

--(for dropdownlist) Schema.name - rowcount, Schema.name from Tables

-----------------------------------------------------------

select

--'['+SCHEMA_NAME(t.[SCHEMA_ID])+'].['+t.NAME+']' AS [fulltable_name],

SCHEMA_NAME

(t.[SCHEMA_ID]) as [schema_name],t.NAME as [table_name] ,i.rows

from

sys.tables t

INNER

JOIN sysindexes i ON (t.object_id = i.id AND i.indid < 2)

SELECT

[TableAndCount]

= '['+SCHEMA_NAME(t.[SCHEMA_ID])+'].['+t.NAME+']' + ' - ' + CAST(i.rows as varchar(10)) + ' Rows',

[Name]

= '['+SCHEMA_NAME(t.[SCHEMA_ID])+'].['+t.NAME+']'

--[RowCount] = MAX(si.rows)

FROM

sys.tables t

INNER JOIN sysindexes i ON (t.object_id = i.id AND i.indid < 2)

ORDER

BY

'['+SCHEMA_NAME(t.[SCHEMA_ID])+'].['+t.NAME+']'

Thursday, December 15, 2011

Display Foreign Key Relationships and Name of the Constraint for Each Table in Database

Generate create script for all Foreign Keys

Original article:  http://connectsql.blogspot.com/2009/07/script-to-create-all-primary-and.html

SELECT

'ALTER TABLE '+OBJECT_NAME(F.PARENT_OBJECT_ID)+ ' ADD CONSTRAINT'

+

F.NAME + ' FOREIGN KEY'+'('+COL_NAME(FC.PARENT_OBJECT_ID,FC.PARENT_COLUMN_ID)+

')'

+'REFRENCES '+OBJECT_NAME (F.REFERENCED_OBJECT_ID)+'('

+

COL_NAME(FC.REFERENCED_OBJECT_ID,FC.REFERENCED_COLUMN_ID)+')'

FROM

SYS.FOREIGN_KEYS AS F

INNER

JOIN SYS.FOREIGN_KEY_COLUMNS AS FC

ON

F.OBJECT_ID = FC.CONSTRAINT_OBJECT_IDGet the Foreign Key Hierarchy

original article:  http://www.sqlservercentral.com/scripts/Maintenance+and+Management/30445/

/******************************************************************************

This script will run through the foreign keys on tables to produce a hierarchy

of the tables in a database.

The heirarchy produced will be :

0 Tables that have no FK relationships at all, as either as 'parents' or

'children'

1 Tables which are at the top of the tree, and have no 'parents', only

'children'

2 ...you can figure it out from here...

If you need to repopulate the database your table order would be 0,1,2...

To delete from tables you need to start at the highest number ...3,2,1,0

*******************************************************************************/

SET

NOCOUNT ON

DECLARE

@intCounter

INT,

@intRowCount

INT

CREATE

TABLE #Hierarchy

(Hierarchy INT,

Child

VARCHAR(100),

Parent

VARCHAR(100))

-- Set the variables

SELECT

@intCounter = 1

SELECT

@intRowCount = 1

-- Populate the table

INSERT

INTO #Hierarchy

SELECT

DISTINCT 1 AS 'Hierarchy', S1.name AS 'Child', SO.Name AS 'Parent'

FROM

dbo.sysforeignkeys FK

INNER

JOIN dbo.sysobjects SO

ON

FK.rkeyID = SO.id

INNER

JOIN dbo.sysobjects S1

ON

FK.fkeyID = S1.id

WHILE

@intRowCount <> 0

BEGIN

UPDATE #Hierarchy

SET Hierarchy = Hierarchy + 1

WHERE Hierarchy = @intCounter

AND Parent IN (SELECT DISTINCT Child

FROM #Hierarchy

WHERE Hierarchy = @intCounter)

SET @intRowCount = @@Rowcount

SELECT @intCounter = @intCounter + 1

END

-- Add the tables that have no Foriegn Key relationships...

INSERT

INTO #Hierarchy

SELECT

-1, [name], ' - '

FROM

dbo.sysobjects

WHERE

[name] NOT IN (SELECT DISTINCT Parent FROM #Hierarchy)

AND

[Name] NOT IN (SELECT DISTINCT Child FROM #Hierarchy)

AND

xtype = 'U'

-- Add the tables that are Parents only

INSERT

INTO #Hierarchy

SELECT

DISTINCT 0, Parent, ' - '

From

#Hierarchy

WHERE

Parent NOT IN (SELECT Child FROM #Hierarchy)

AND

Hierarchy <> -1

-- Add 1 to adjust the hierarchies to start at 0

UPDATE

#Hierarchy

SET

Hierarchy = Hierarchy + 1

-- Display the results

SELECT

DISTINCT Hierarchy, Child, Parent

FROM

#Hierarchy

ORDER

BY Hierarchy, Child, Parent

-- Clean up

DROP

TABLE #Hierarchy

Display Foreign Key Relationships and Name of the Constraint for Each Table in Database

 

Original Article:  http://blog.sqlauthority.com/2006/11/01/sql-server-query-to-display-foreign-key-relationships-and-name-of-the-constraint-for-each-table-in-database/

 

I changed to version below to

1) show PK to the left

2) trim the result columns

 

SELECT

PK_Table =Left(PK.TABLE_NAME, 35),

PK_Column =Left(PT.COLUMN_NAME, 12),

FK_Table =Left(FK.TABLE_NAME, 25),

FK_Column =Left(CU.COLUMN_NAME, 20),

Constraint_Name = C.CONSTRAINT_NAME

FROM INFORMATION_SCHEMA . REFERENTIAL_CONSTRAINTS C

INNER JOIN INFORMATION_SCHEMA . TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME

INNER JOIN INFORMATION_SCHEMA . TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME

INNER JOIN INFORMATION_SCHEMA . KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME

INNER JOIN (

SELECT i1.TABLE_NAME, i2.COLUMN_NAME

FROM INFORMATION_SCHEMA . TABLE_CONSTRAINTS i1

INNER JOIN INFORMATION_SCHEMA . KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME

WHERE i1.CONSTRAINT_TYPE ='PRIMARY KEY'

) PT ON PT.TABLE_NAME = PK.TABLE_NAME

---- optional:

ORDER BY

--1,2,3,4

PK_Table, FK_Table

--WHERE PK.TABLE_NAME='something'WHERE FK.TABLE_NAME='something'

--WHERE PK.TABLE_NAME IN ('one_thing', 'another')

--WHERE FK.TABLE_NAME IN ('one_thing', 'another')

 

Friday, November 11, 2011

FTP Upload ftpWebRequest Proxy

Searchable:
 
FTP Upload ftpWebRequest Proxy
FTP command is not supported when using HTTP proxy

 

 
In the article below I will cover 2 topics
 
1.       C# & Windows Command-Line FTP Upload with No Proxy Server
 
2.       C# & Windows Command-Line FTP Upload with Proxy Server
 
Not covered here: Secure FTP / SFTP
 
Sample Attributes:
·         UploadFilePath = “\\servername\folder\file.name
·         Proxy Server = ftp://proxy.server/
·         FTP Target Server = ftp.target.com
·         FTP User = “User”
·         FTP Password = “Password”
with No Proxy Server
·         Windows Command-Line
> ftp User: User
> ftp Password: Password
> ftp dir
          (result: file.name listed)
> ftp del file.name
> ftp dir
          (result: file.name deleted)
> ftp quit
 
·         C#
 
//-----------------
//Start FTP via _TargetFtpProxy
//-----------------
string relPath = Path.GetFileName(\\servername\folder\file.name);
 
//result: relPath = “file.name”
 
FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create("ftp.target.com/file.name);
ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
 
//-----------------
//user - password
//-----------------
ftpWebRequest.Credentials = new NetworkCredential("user, "password");
 
//-----------------
// set proxy = null!
//-----------------
ftpWebRequest.Proxy = null;
 
//-----------------
// Copy the contents of the file to the request stream.
//-----------------
StreamReader sourceStream = new StreamReader(“\\servername\folder\file.name);
 
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
ftpWebRequest.ContentLength = fileContents.Length;
 
 
//-----------------
// transer the stream stream.
//-----------------
Stream requestStream = ftpWebRequest.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
 
//-----------------
// Look at the response results
//-----------------
FtpWebResponse response = (FtpWebResponse)ftpWebRequest.GetResponse();
 
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
 
with Proxy Server
·         Windows Command-Line
> ftp proxy.server
> ftp User: User@ftp.target.com
> ftp Password: Password
> ftp dir
          (result: file.name listed)
> ftp del file.name
> ftp dir
          (result: file.name deleted)
> ftp quit
 
·         C#
 
//-----------------
//Start FTP via _TargetFtpProxy
//-----------------
string relPath = Path.GetFileName(\\servername\folder\file.name);
 
//result: relPath = “file.name”
 
FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create("ftp://proxy.server/" + relPath);
ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
 
//-----------------
//user - password
//-----------------
ftpWebRequest.Credentials = new NetworkCredential("user@ftp.target.com, "password");
 
//-----------------
// set proxy = null!
//-----------------
ftpWebRequest.Proxy = null;
 
//-----------------
// Copy the contents of the file to the request stream.
//-----------------
StreamReader sourceStream = new StreamReader(“\\servername\folder\file.name);
 
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
ftpWebRequest.ContentLength = fileContents.Length;
 
 
//-----------------
// transer the stream stream.
//-----------------
Stream requestStream = ftpWebRequest.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
 
//-----------------
// Look at the response results
//-----------------
FtpWebResponse response = (FtpWebResponse)ftpWebRequest.GetResponse();
 
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

Friday, October 14, 2011

Invalid value for 'OSVersion'

Invalid value for 'OSVersion'

 Thanks to Mike Wade @ Microsoft

I would recommend clearing the environment variable, or better yet, adding the following to the project file:

  <PropertyGroup>
    <OSVersion></OSVersion>
  </PropertyGroup>

This will fully override the environment variable and blank it out.  The task should then set this to a better default value.

Monday, October 10, 2011

Oracle Dynamic SQL – Drop Table, Copy Table, Purge Tables

Oracle Dynamic SQL – Drop Table, Copy Table, Purge Tables       
 
 
CREATEORREPLACEPROCEDURE COMPLIANCE11.table_drop (table_name VARCHAR2) IS
    dml_str
VARCHAR2        (500);
BEGIN
    dml_str :=
'DROP TABLE ' || table_name ;
   
EXECUTEIMMEDIATE dml_str ;
END;
 
 
 
void the_Table_Housekeeping()
        {
            try
            {
 
                string JobDateTime_string = _jobDateTime.ToString("yyyy-MM-dd_HH-mm-ss");
                JobDateTime_string = JobDateTime_string.Replace("-", "");
                JobDateTime_string = JobDateTime_string.Replace("_", "");
 
                Microsoft_Enterprise_Library.Oracle.OracleAccessLayer objData = new Microsoft_Enterprise_Library.Oracle.OracleAccessLayer();
 
 
                //-----------------------------------
                // look for dupe table before drop table
                //-----------------------------------
 
                string ssql = "select nvl((select 1 from user_tables where table_name='THE_" + JobDateTime_string + "' and rownum=1),0) from dual";
                DataTable dt = objData.GetDataTableFromOracleSQL(ssql, this._Oracle_Compliance11connectionString);
                if (dt.Rows.Count < 1)
                {
                    throw new Exception("dt.Rows.Count < 1");
                }
                int found = int.Parse(dt.Rows[0][0].ToString());
 
                OracleCommand oracleCommand = new OracleCommand();
                if (found == 1)
                {
                    //-----------------------------------
                    // drop table
                    //-----------------------------------
                    oracleCommand.CommandText = "table_Drop";
                    oracleCommand.Parameters.Clear();
                    oracleCommand.Parameters.Add("table_name", OracleType.VarChar).Value = "THE_" + JobDateTime_string;
                    int rowsAffected = objData.GetRowsAffected_From_StoredProc(this._Oracle_Compliance11connectionString,
                                                                                oracleCommand);
                }
 
                //-----------------------------------
                // does not work, "insufficient privileges"
                //-----------------------------------
                //oracleCommand.CommandText = "table_copy";
                //oracleCommand.Parameters.Clear();
                //oracleCommand.CommandType = CommandType.StoredProcedure;
                //oracleCommand.Parameters.Add("table_name_orig", OracleType.VarChar).Value = "THE_Table";
                //oracleCommand.Parameters.Add("table_name_new", OracleType.VarChar).Value = "THE_" + JobDateTime_string;
                //int rowsAffected2 = objOracle.GetRowsAffected_From_StoredProc_Transaction();
 
                //-----------------------------------
                // create table
                //-----------------------------------
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("CREATE TABLE THE_" + JobDateTime_string + " AS (SELECT * FROM THE_Table)");
                string mySQL = sb.ToString();
                oracleCommand.CommandType = CommandType.Text;
                int rowsAffected2 = objData.ExecuteNonQuery_SQL(
                                                mySQL,
                                                this._Oracle_Compliance11connectionString,
                                                false);
 
                //-----------------------------------
                // purge to 4 previous copies
                //-----------------------------------
                sb = new StringBuilder();
                ssql = "select table_name from user_tables where table_name LIKE 'THE_2%' order by table_name asc";
                dt = objData.GetDataTableFromOracleSQL(ssql, this._Oracle_Compliance11connectionString);
 
                for (int i = 0; i < dt.Rows.Count - 4; i++)
                {
                    string table_name = dt.Rows[i][0].ToString();
                    //-----------------------------------
                    // drop table
                    //-----------------------------------
                    oracleCommand.CommandText = "table_Drop";
                    oracleCommand.Parameters.Clear();
                    oracleCommand.Parameters.Add("table_name", OracleType.VarChar).Value = table_name;
                    int rowsAffected = objData.GetRowsAffected_From_StoredProc(this._Oracle_Compliance11connectionString,
                                                                                oracleCommand); ;
                }
 
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
 
 

Thursday, October 6, 2011

OpenXML SDK 2.0: Export a DataTable to Excel

OpenXML SDK 2.0: Export a DataTable to Excel

Very good article and download project

http://lateral8.com/articles/2010/3/5/openxml-sdk-20-export-a-datatable-to-excel.aspx

 

The DocumentFormat.OpenXml.dll is registered in the GAC when the SDK is installed so it doesn't physically copy it to your project's output folder by default when you build the application.  If you select the option to Show All Files in Visual Studio (Project | Show All Files), you'll see a References node appear in your VB.NET project in the Solution Explorer.  Expand it, select DocumentFormat.OpenXml, view it's properties, and set the Copy Local option to True so that it copies it to the output folder when you build the app.  You can then copy it along with the app to any other PC and it will run without having to install the SDK on them.

 

Wednesday, August 10, 2011

Debug Web Part installed in GAC

Debug Web Part installed in GAC

Thanks to  Doug Ware @ Elumenotion > Elumenotion Blog > Posts > You Don't Need to Copy PDB Files to Debug in the GAC!
11/12/2007
 
 

Thursday, July 28, 2011

ASP.NET Detect and alert forms authentication timeout

ASP.NET Detect and alert forms authentication timeout
 
1.      Add sessionState to web.config
 <system.web>
        <sessionStatetimeout="1"mode="InProc" /> <!--minutes e.g. 120 = 2 hours-->
 
2.      Add  FormsAuthentication to web.config
    <authenticationmode="Forms">
      <!--timeout minutes (needs to be the same as in sessionState above) e.g. 120 = 2 hours-->
      <!--loginUrl - destination when FormsAuthentication Times out -->
      <!--defaultUrl - where FormsAuthentication.RedirectFromLoginPage goes, unless user overrode with valid URL in browser-->
      <formsloginUrl="~/Forms/Logon.aspx"                        
             defaultUrl="~/Forms/OrderCreate.aspx?TimeOut=True"
             protection="All"
             timeout="1"
             name=".ASPXAUTH"
             path="/"
             requireSSL="false"
             slidingExpiration="true"
             cookieless="UseDeviceProfile"
             enableCrossAppRedirects="false"/>
    </authentication>
 
3.      On Session_Start, detect session timeout and set a “CatchTimeOut” session variable
 void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        // no - Response.Cookies["CoprSession"].Value = ""; //.Expires = DateTime.Now.AddDays(5000);
 
 
        //This is obviously a new session being created; it can be
        //created at the first hit of a user, or when the user
        //previous session has expired (timeout). We are only interested
        //in the timeout scenario, so we look at the request cookies
        //and if we have a previous session ID cookie, it means this is a
        //new session due to the timing out of the old one.
        //Note: slight problem here: in .Net 2.0 the ASP Session ID
        //cookie name is configurable, but we don't have a way to
        //retrieve that from the web.config - so if you customize
        //the session cookie name in the web.config you'll have to
        //use the same name here.
        string request_cookies = Request.Headers["Cookie"];
        if ((null != request_cookies) &&
                (request_cookies.IndexOf("ASP.NET_SessionId") >= 0))
        {
            //cookie existed, so this new one is due to timeout.
            //Redirect the user to the login page
            //System.Diagnostics.Debug.WriteLine("Session expired!");
 
            //Response.Redirect(Constants.HOME_PAGE + "?" +
 
            //                  Constants.PARAM_REQUEST + "=" +
 
            //                  Constants.PARAM_REQUEST_VALUE_TIMEOUT);
            Session[“CatchTimeOut”] = true;
        }
    }
4.      Create a base page to query the “CatchTimeOut” session variable and do a javascript alert
public class _BasePage : System.Web.UI.Page
{
    protected override void OnLoad(EventArgs e)
    {
 
        // Be sure to call the base class's OnLoad method!
        base.OnLoad(e);
 
 
        //-----------------------------------------------------------------------
        //
        //-----------------------------------------------------------------------
        if (Session[“CatchTimeOut”])
        {
            Session[“CatchTimeOut”] = false;
            string strScript = "<script>alert('Your web session timed out.');</script>";
            Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "ShowInfo", strScript);
        }
    }
}
5.      Inherit base page wherever base behavior is needed
·         public partial class LnumberSearch : _BasePage
·        {