public class ben:harrell

July 10, 2007

SSIS Row Limits and DefaultBufferMaxRows

Filed under: C#, database, errors, Integration Servicees, SQL Server 2005, SSIS, Technology — benjamin harrell @ 9:51 pm

I had an odd issue during some testing I was doing on a custom source component I’m writing for EBCDIC data conversion.  I first assumed that surely my code was at fault but the test just seemed to simple to be “my code”.  So here’s the scenario,  I have a file with 100,000 bytes of the number ‘1’ in EBCDIC.  I created a simple package to import the file as 1 byte rows into a Dataset Destination.  I was surprised when I executed the package and found that only 65,536 rows were processed.  Now if you have been around software for more than a week you probably recognize this magic number and unfortunately it triggers all sorts of theories about what could possibly be going wrong.  Well, I’m still trying to investigate the “why” and I’ll update this post and welcome comments if anyone has input but for now the solution to this oddity is to increase the DefaultBufferMaxRows to greater than your number of records.  This seems like a horrible workaround for a situation that should happen quite often so the hunt continues…

June 18, 2007

UPDATE: Cannot open user default database. Login failed. Login failed for user ‘UserName’. (Microsoft SQL Server, Error: 4064)

Filed under: database, dba, SQL Server 2005 — benjamin harrell @ 10:24 am

 Thanks to Fritz Laurel for adding this in the comments section, after you gain access you may need to run this script to store the new default database for the Login you used.

ALTER LOGIN loginid
WITH DEFAULT_DATABASE = master
GO

March 1, 2007

Reporting Services 2005 Rotation and Orientation

Filed under: .NET, ASP.NET, C#, Reporting Services 2005, SQL Server 2005, Technology — benjamin harrell @ 4:54 pm

As many of you might have figured out by now Reporting Services 2005 doesn’t support rotating objects or multiple orientation (as in per sub report).  Depending on your situation there might still be an answer.  I was in a situation recently where I need certain pages of a report in landscape and some in portrait.  I was told that this is not possible out of the box in Reporting Services 2005 but have since found a workaround that might work for you.  Microsoft has done a great job with making SSRS an open architecture and the web services are a key part of this approach.  Behind the scenes of your Report Viewer control (in “remote” mode) it is actually making a request to the Render command of the SSRS Web Service.  So to pull of the rotation of a report I created a new web page with a web reference to the ReportService.  I then request the report in IMAGE format and store the byte[].  I create a new Bitmap object and stream in the byte[] so that I have full control over my newly created report Image in GDI.NET.  Bitmap supports a RotateFlip method that has just what we need and then I save the Bitmap to the Response.OutputStream object.  You are probably familiar with the concept of pointing an Image to an ASPX page that dynamically generates the bytes of the Image and this solution is no different.  Once you have an ASPX that can generate a rotated Image of the report then you treat it just like any other Image in the Report or on a WebForm.

This solution was adapted from Bryan Kelly’s post on Programmatically Printing RS 2000 Reports found HERE

The source code for the page is below:

 using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing.Imaging;
using System.Drawing;
using System.Runtime.InteropServices; // For Marshal.Copy
using System.IO;
using System.Web.Services.Protocols;

public partial class ASR_ReportAsImage : System.Web.UI.Page
{
    ReportService.ReportingService rs;
    private byte[][] m_renderedReport;
    private System.Drawing.Graphics.EnumerateMetafileProc m_delegate = null;
    private System.IO.MemoryStream m_currentPageStream;
    private System.Drawing.Imaging.Metafile m_metafile = null;
    int m_numberOfPages;
 
    protected void Page_Load(object sender, EventArgs e)
    {
       
        rs = new ReportService.ReportingService();
        rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
        PrintReportAsImage();
    }

    public byte[][] RenderReport(string reportPath)
    {
        // Private variables for rendering
        string deviceInfo = null;
        string format = “IMAGE”;
        Byte[] firstPage = null;
        string encoding;
        string mimeType;
        ReportService.Warning[] warnings = null;
        ReportService.ParameterValue[] reportHistoryParameters = null;
        string[] streamIDs = null;
        Byte[][] pages = null;

        // Build device info based on the start page
        deviceInfo =
           String.Format(@”<DeviceInfo><OutputFormat>{0}</OutputFormat></DeviceInfo>”, “emf”);

        //Exectute the report and get page count.

        // Renders the first page of the report and returns streamIDs for
        // subsequent pages
        firstPage = rs.Render(
           reportPath,
           format,
           null,
           deviceInfo,
           null,
           null,
           null,
           out encoding,
           out mimeType,
           out reportHistoryParameters,
           out warnings,
           out streamIDs);
        // The total number of pages of the report is 1 + the streamIDs        
        m_numberOfPages = streamIDs.Length + 1;
        pages = new Byte[m_numberOfPages][];

        // The first page was already rendered
        pages[0] = firstPage;

        for (int pageIndex = 1; pageIndex < m_numberOfPages; pageIndex++)
        {
            // Build device info based on start page
            deviceInfo =
               String.Format(@”<DeviceInfo><OutputFormat>{0}</OutputFormat><StartPage>{1}</StartPage></DeviceInfo>”,
                 “emf”, pageIndex + 1);
            pages[pageIndex] = rs.Render(
               reportPath,
               format,
               null,
               deviceInfo,
               null,
               null,
               null,
               out encoding,
               out mimeType,
               out reportHistoryParameters,
               out warnings,
               out streamIDs);
        }

        return pages;
    }

    public bool PrintReportAsImage()
    {
        this.RenderedReport = this.RenderReport(“/ASR Prototype/ASR_TransactionOverview”);

        // Wait for the report to completely render.
        if (m_numberOfPages < 1)
            return false;

        for (int i = 0; i < m_renderedReport.Length; i++)
        {
            //write all of the pages to stream….

            System.IO.MemoryStream memstream = new System.IO.MemoryStream(m_renderedReport[i], false);
            System.Drawing.Bitmap oBitmap = new System.Drawing.Bitmap(memstream, true);
            //now rotate the bitmap 90 degrees
            oBitmap.RotateFlip(RotateFlipType.Rotate270FlipNone);
            //write it to the output stream
            Response.ContentType = “image/jpeg”;
            oBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);

        }
        return true;
    }
 

    // Method to draw the current emf memory stream
    private void ReportDrawPage(Graphics g)
    {
        if (null == m_currentPageStream || 0 == m_currentPageStream.Length || null == m_metafile)
            return;
        lock (this)
        {
            // Set the metafile delegate.
            int width = m_metafile.Width;
            int height = m_metafile.Height;
            m_delegate = new Graphics.EnumerateMetafileProc(MetafileCallback);
            // Draw in the rectangle
            Point destPoint = new Point(0, 0);
            g.EnumerateMetafile(m_metafile, destPoint, m_delegate);
            // Clean up
            m_delegate = null;
        }
    }
    private bool MoveToPage(Int32 page)
    {
        // Check to make sure that the current page exists in
        // the array list
        if (null == this.RenderedReport[m_currentPrintingPage – 1])
            return false;
        // Set current page stream equal to the rendered page
        m_currentPageStream = new MemoryStream(this.RenderedReport[m_currentPrintingPage – 1]);
        // Set its postion to start.
        m_currentPageStream.Position = 0;
        // Initialize the metafile
        if (null != m_metafile)
        {
            m_metafile.Dispose();
            m_metafile = null;
        }
        // Load the metafile image for this page
        m_metafile = new Metafile((Stream)m_currentPageStream);
        return true;
    }
    private bool MetafileCallback(
       EmfPlusRecordType recordType,
       int flags,
       int dataSize,
       IntPtr data,
       PlayRecordCallback callbackData)
    {
        byte[] dataArray = null;
        // Dance around unmanaged code.
        if (data != IntPtr.Zero)
        {
            // Copy the unmanaged record to a managed byte buffer
            // that can be used by PlayRecord.
            dataArray = new byte[dataSize];
            Marshal.Copy(data, dataArray, 0, dataSize);
        }
        // play the record.     
        m_metafile.PlayRecord(recordType, flags, dataSize, dataArray);

        return true;
    }
    public byte[][] RenderedReport
    {
        get
        {
            return m_renderedReport;
        }
        set
        {
            m_renderedReport = value;
        }
    }

}

January 15, 2007

Cannot open user default database. Login failed. Login failed for user ‘UserName’. (Microsoft SQL Server, Error: 4064)

Filed under: database, dba, errors, SQL Server 2005 — Tags: , , , , , , — benjamin harrell @ 8:28 pm

Cannot open user default database. Login failed. Login failed for user ‘UserName’. (Microsoft SQL Server, Error: 4064)

This error bugged the crap out of me tonight and I saw all kinds of crazy answers usually involving some sort of SQLCMD -blah -blah…i think this maybe the problem with command line happy developers/dbas but to make a long story short the fix is EASY and you will kick yourself for not trying this.

1.  click the options button if the options are not showing.

2.  click the connection properties tab if it is not active

3.  click on the Connect to database: dropdown

4.  type in the name of a database that still exists (ex. ‘master’)

5. connect!

I heard all kinds of rants and raves about how atrocious it was that microsoft did this to us and I agree it does suck that SQL Server doesn’t do something about this automagically but what would you suggest it do?

 

 

[UPDATE]  I wanted to move some of the great ideas in the comments to the top so that people could find other solutions more quickly:

From Commenter Fritz Laurel:

ALTER LOGIN loginid
WITH DEFAULT_DATABASE = master
GO

From commenter Das:

For those of you who use their Domain accounts, here is the Alter statement to run once you assign the MASTER DB from the above step.

ALTER LOGIN [BUILTIN\Administrators] WITH DEFAULT_DATABASE=master

Replace [BUILTIN\Administrators] with your [domain\usr]

NOTE:[Brackets] required on Domain\User accounts

From commenter Breb02 (SQL 2000?)

RUN–>cmd
sqlcmd -E -d master (osql -E -d master for SQL 2000)
1>sp_defaultdb ‘Computer\username’, ‘master’
2>go

Later SQL Server versions:
sqlcmd -E -d master

From commenter Fuad Ahmed

And the solution for me was just switching the registration property of the server from sql authentication to windows authentication.

I think I was lucky that the login sa had different default database and the windows authentication had different.

From commenter Tony G

I’m using VS2008 Server Explorer. I opened Modify Connection, Advanced Properties, and just set User Instance to true. That allowed my local SQL Server to open the local mdf. HTH

From commenter BobG

I had to.. Under my “registered servers” list, pick the offending server/instance and then right click, choosing “properties”, then choosing “connection properties”, and then type in a database name in the offending server/instance in the “Connect to database:” drop down box.

Then I was able to get in but no offered choices from this post worked for me beyond getting back in, and I had very little rights/access.
I wound up deleting my login from the Server/instance under “Security”. Then I was able to close MS SQL Studio and went back in without further issue.
Note: I also have that same account, a domain account, that I had deleted listed under other SQL Domain Groups for the offending server/instance.

From commenter PeterG

I am running Win7x64 and once of a sudden could not open my DB anymore. I ended up having to “take ownership” of the folder with the DB inside and viola – it worked

From commenter Adrian

To repair an an SQL Server 2000 with default db detached I made the following :

1. I used SQL Server 2005 management console from a client PC and get connected to the server to another existing database;

2. Created another user :
EXEC sp_addlogin ‘Adrian’, ‘p1234′

3. Re-attached the default database with :
EXEC sp_attach_db @dbname = ‘ATOTAL’,
@filename1 = ‘C:\ATOTAL DB\atotal_Data.MDF’,
@filename2 = ‘C:\ATOTAL DB\atotal_LOG.LDF’

From commenter spiritos

I couldn’t connect either (default db not found) so tried this fix but I couldn’t even browse the server to select a new db to use. As a result I started looking at the Security for the db… turns out there was a db that was restored (just happened to be my normal login’s default db!) but in the process some Users had been dropped from the Security folder – including the group that my “normal” login belonged to! Added these groups back in then could connect again!

From commenter One IT Services

You don’t have to use any commands at all, if you still have a login that works then use that to first login to the object explorer.
If you don’t then when logging in make sure you do as stated in the blog which was to click the options button on the Connect to Server Screen.
Then on Connect to Database just click Browse Server, say yes to connect and select any database from the list.
Then once you’re in the Object Explorer, expand Security, Logins and select the username you need to fix.
At the bottom of the Login Properties box you just need to select a Default Database, most likely Master.

From commenter vishalsharma

Note : you have to type master in default database drop down. You won’t see it there in the list.

 

I hope some of these most appreciated comments will help others!

October 7, 2006

Object Data Source Gotcha

Filed under: Uncategorized — benjamin harrell @ 10:37 pm

So you just created your super cool Business Object and you want to bind some control to it but when you add new data source you can’t see your object!!!

Not to worry, if you can’t see your object try this:

  1. cancel out of the dialog
  2. rebuild your project
  3. now re-add the datasource

Not sure how or why but, as usual, Visual Studio is caching objects 🙂

Team Foundation Server install – where is kb912838?

Filed under: Uncategorized — benjamin harrell @ 10:34 pm

…it is in the sql server kb folder called kb 914595

TreeView Render Speed

Filed under: .NET, Technology — benjamin harrell @ 10:15 pm

Here is a quick tip when doing large updates and adds to the Windows Forms Treeview control. Use the beginupdate() method to “turn off” rendering and then after your changes are complete use the endupdate() method to turn rendering back on which will then render all of your changes.

Sometimes it is necessary to do this for a control that doesn’t have these wonderful methods but no to worry you can easily derive a control, add your own “flag” variable and then just override the OnPaint method and if your variable is set to not render then simply return from OnPaint. I have also added the Begin and EndUpdate methods below for setting the variable. If you want to force the control to repaint then you can call EndUpdate( true ). Here is a sample :

public class FastDrawTreeView : System.Windows.Forms.TreeView
{
private bool _disableRendering = false;

public void BeginUpdate()
{
_disableRendering = true;
}

public void EndUpdate(bool redraw)
{
_disableRendering = false;
if (redraw)
this.Refresh();
}

protected override void OnPaint(PaintEventArgs e)
{
if (_disableRendering)
return;
base.OnPaint(e);
}
}

July 29, 2006

ASP.NET 2.0 where are my references!!!!

Filed under: .NET, Technology, Visual Studio — benjamin harrell @ 6:27 pm

ASP.NET 2.0 web projects have references but don’t show them as a ‘References’ folder in the project.  This might be a preference setting buried somewhere in the options page but for now it is easy enough just to right-click the project and choose the menu item ‘Property Pages’.  You will get a screen like below where you can manage both project and web references.   

 Project Properties Page

July 27, 2006

Usability and ASP.NET Site Navigation

Filed under: .NET, Design, Uncategorized, Usability — benjamin harrell @ 6:50 pm

I recently started looking into ASP.NET Site Navigation and the sitemap controls.  Orginally, discounted the sitemap control as something you would drop on a page called sitemap and never touch again but boy was I wrong.  Site Navigation is an entire API for controlling site naviation in a consitent and near drag and drop manner.  And as usual, the 2.0 team hit another home run witht he Provider model allowing you to drive your Sitemap data from any source (XML out of the box but there are already multiple SQL implementations but my favorite is Jeff Prosise’s found here for MSDN magazine).  So what does this have to do with Usability?  Well, today I noticed something very related to Usability in the real world and it immediately hit me that we as developers make the same mistake all the time.  What cardinal Usability sin am I talking about?  Don’t put it there if I am not supposed to use it! I noticed an irate man yanking on a fancy, obvious door ‘pull bar’ and in small print next to it was printed ‘Push’.  Sure it makes for a great joke and even a classic Far Side but this really is a design/usability error!  Why wasn’t there a flat panel that said ‘Push’ on it?  Why the pull bar!!!  Ok so what does this have to do with Site Navigation….well, only the coolest feature in my opinion:

 ASP.NET 2.0’s site navigation provides a feature called security trimming. When obtaining site map information with security trimming enabled, only those site map nodes that the currently logged on user has authorization to visit are available. That means the site’s TreeView or Menu will contain just those sections accessible by the currently logged in user.

I pulled this from a great series on Site Navigation here

Really all you have to do is turn on SecurityTrimming in the web.config as shown below:

 <siteMap defaultProvider=”XmlSiteMapProvider” enabled=”true”>
   <providers>    
     <add name=”XmlSiteMapProvider”      
       description=”Default SiteMap provider.”  
       type=”System.Web.XmlSiteMapProvider”  
       siteMapFile=”siteMapFileName”      
       securityTrimmingEnabled=”true” />  
   </providers>
</siteMap>

That’s it!  Of course you have the ability to override for certain items but I’ll leave that as an exercise to the reader.  Now all we need is a good visual studio Add-In to generate a sitemap file or SQL database script from my current website project…I guess I better get that project started!

July 26, 2006

Web Parts Manager personalization without SQLExpress

Filed under: .NET, Technology — benjamin harrell @ 3:15 pm

Earlier I posted about wanting to put personalization on a separate SQL instance (not local).  Well, this gives me a chance to say thanks to the MSDN2 team for making more information available in .NET 2.0.  I was a little worried during the BETA because of so many empty pages but MSDN is loaded with good information and plenty of walkthroughs!  There is even a MSDN WIKI found here .  OK here is the answer I promised: 

Personalized settings are not tied to a single browser session. Because they are stored in long-term storage, the application can retrieve a user’s settings each time the user visits a specific page.

Personalization uses an ASP.NET application services database to store personalization data. By default, ASP.NET creates this database automatically in a subfolder named “app_data” when an ASP.NET application first uses personalization or one of the other application services such as roles, membership or profiles. Also by default, ASP.NET creates the database as a single SQL Server Express database file that contains the database schema for all of the application services. Using the Web.config file, you can configure your application so that a separate database file is created for personalization. Further, in the Web.config file, you can specify a SQL Server database to store the application services data instead of using the default SQL Server Express database file.

The mechanism for storing and retrieving personalization data consists of a provider component and a data store. ASP.NET includes a default Microsoft SQL provider and database. You can also create a custom provider and configure it to use any data store.  (THANK GOD!  gotta love the new provider model)

essentially this is the web.config section you need under <system.web>

(the MSDN entry is here for the element)

<webParts><personalization ><providers>

<remove name=AspNetSqlPersonalizationProvider />        

<add connectionStringName=my_connection_stringname=AspNetSqlPersonalizationProvider

type=System.Web.UI.WebControls.WebParts.SqlPersonalizationProviderapplicationName=//>

 </providers></personalization></webParts>

Some of this was information was found in a really good article on personalization here . 


 

technorati tags:, , ,

« Newer PostsOlder Posts »

Create a free website or blog at WordPress.com.