Wednesday, December 7, 2011

SqlDataAdapter To Retrieve Multiple Rows


SqlDataAdapter To Retrieve Multiple Rows

The following code illustrates how to use a SqlDataAdapter object to issue a command that generates a DataSet or DataTable. It retrieves a set of product categories from the SQL Server Northwind database.

using System.Data;

using System.Data.SqlClient;



public DataTable RetrieveRowsWithDataTable()

{

  using ( SqlConnection conn = new SqlConnection(connectionString) )

  {

    conn.Open();

    SqlCommand cmd = new SqlCommand("DATRetrieveProducts", conn);

    cmd.CommandType = CommandType.StoredProcedure;

    SqlDataAdapter adapter = new SqlDataAdapter( cmd );

    DataTable dataTable = new DataTable("Products");

    adapter .Fill(dataTable);

    return dataTable;

  }

}

 


To use a SqlAdapter to generate a DataSet or DataTable

1. Create a SqlCommand object to invoke the stored procedure and associate this with a SqlConnection object (shown) or connection string (not shown).
2. Create a new SqlDataAdapter object and associate it with the SqlCommand object.
3. Create a DataTable (or optionally, a DataSet) object. Use a constructor argument to name the DataTable.
4. Call the Fill method of the SqlDataAdapter object to populate either the DataSet or DataTable with the retrieved rows.

Reading BLOG Data from the Database

Reading BLOB Data from the Database

When creating a SqlDataReader object through the ExecuteReader method to read rows that contain BLOB data, use the CommandBehavior.SequentialAccess enumerated value. Without this enumerated value, the reader pulls data from the server to the client one row at a time. If the row contains a BLOB column, this might represent a large amount of memory. By using the enumerated value, you have a finer degree of control because the BLOB data will be pulled only when referenced (for example, by means of the GetBytes method, which you can use to control the number of bytes read). This is illustrated in the following code fragment.

Writing BLOG Data to the Database



Writing BLOG Data to the Database
public void  StorePicture( string filename )
 {
   // Read the file into a byte array
   using(FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
   {
     byte[] imageData = new Byte[fs.Length];
     fs.Read( imageData, 0, (int)fs.Length );
   }
   using( SqlConnection conn = new SqlConnection(connectionString) )
   {
     SqlCommand cmd = new SqlCommand("StorePicture", conn);
     cmd.CommandType = CommandType.StoredProcedure;
     cmd.Parameters.Add("@filename", filename );
     cmd.Parameters["@filename"].Direction = ParameterDirection.Input;
     cmd.Parameters.Add("@blobdata", SqlDbType.Image);
     cmd.Parameters["@blobdata"].Direction = ParameterDirection.Input;
     // Store the byte array within the image field
     cmd.Parameters["@blobdata"].Value = imageData;
     conn.Open();
     cmd.ExecuteNonQuery();
   conn.Close();
   }
 }

Bringing SelectedItem Into Focus Using DataGrid Control

Problem :
              When using datagrid control of the silverlight control there is situation when datagrid control has lots of records and vertical scrolling of the datagrid control is visible and the selected item of the datagrid control is not in the view as the scrolling (vertical scrolling of the datagrid is visible due to large record). So it is important to give focus to the selected item of the datagrid control.In this post I will give you solution of this problem which many of you may have face.
Solution :
               To start with how to solve above problem I have one button control with is used to bring the selected item of the datagrid control in the focus and one datagrid control which is used to show the records. The main form of the test application is shown in the Image 1 here you can see that datagrid display all the records which are assign to it ( as I have small number of records in my grid so i have reduce the height of the datagrid control so that it has vertical scrolling and the selected item is not seen when datagrid control first display). In the Image 1 you can see that selected item is not displayed which I have mention in my problem.

Image 1
The solution to above problem is quite simple but it take time when I first come across this problem. You can see the code used to bring the selected item of the datagrid control in the focus just one line of code which is used. Here I have used ScrollIntoView function of the datagrid control which take The data item (row) to scroll to as its first parameter ( here you can see that I have passed the selected item of the datagrid control) and the second parameter of the ScrollIntoView is the column of the datagrid control(the column to scroll to here I have passed the first column of the datagrid control).
?
1
2
3
4
private void Button_Click(object sender, RoutedEventArgs e)
{
    dgrdCustomer.ScrollIntoView(dgrdCustomer.SelectedItem, dgrdCustomer.Columns[0]);
}

List 1
The output can be seen in the Image 2, when you client the "Selected Item" button then it will focus the selected item of the datagrid control.

Image 2
Note: In the HomeViewModel which is the viewModel for the home page. I have assigned value to the Selectedcustomer before sorting the PagedCollectionView(CustomerList property) so that after sorting the selected item will disappear from the view and it should.If I assigned the first element of the PagedCollectionView (CustomerList) after sorting then first element will be selected..

If you have similar situation then you solved it by using above technique as I have done when I got similar situation.You can download the source code from here
 

How to Display Dynamic Images in Crystal Report


How to use Dynamic images in Crystal Report with out Using Database



Step 1: Add Pictures in Crystal report and Suppress all the pictures

For example:
let us Consider 5 pictures A,B,C,D,E. Add those Pictures using Insert Picture Proberty After Adding just supress the all 5 Pictures.

Step 2:
In Your Asp.net Page Just check the the condition according to that remove Suppress option



Code:

using crystalDecisions.Shared;
using crystalDecisions.crystalReports.Engine;

ReportDocument crDoc=new ReportDocument();
crDoc.load(crystalreportpath,OpenReportMethod.OpenReportByTempCopy);
if(id=="A")
{
 crDoc.ReportDefinition.Sections("SectionNameinCrystalReport")
.ReportOject("PicturelabelName").ObjectFormat.EnableSuppress=False
}
else if(id=="B")
{
 crDoc.ReportDefinition.Sections("SectionNameinCrystalReport")
.ReportOject("PicturelabelName").ObjectFormat.EnableSuppress=False
}
else if(id=="C")
{
 crDoc.ReportDefinition.Sections("SectionNameinCrystalReport")
.ReportOject("PicturelabelName").ObjectFormat.EnableSuppress=False
}
else if(id=="D")
{
 crDoc.ReportDefinition.Sections("SectionNameinCrystalReport")
.ReportOject("PicturelabelName").ObjectFormat.EnableSuppress=False
}
else if(id=="E")
{
 crDoc.ReportDefinition.Sections("SectionNameinCrystalReport")
.ReportOject("PicturelabelName").ObjectFormat.EnableSuppress=False
}

Sunday, August 28, 2011

Fck editor Cs File , Fck Editor Dll alternative

using System ;
using System.Web.UI ;
using System.Web.UI.WebControls ;
using System.ComponentModel ;
using System.Text.RegularExpressions ;
using System.Globalization ;
using System.Security.Permissions ;

namespace External.FCKeditorAdaptor
{
    public enum LanguageDirection
    {
        LeftToRight,
        RightToLeft
    }

    [ DefaultProperty("Value") ]
    [ ValidationProperty("Value") ]
    [ ToolboxData("<{0}:FCKeditor runat=server></{0}:FCKeditor>") ]
    [ Designer("DotShoppingCart.OpenSource.External.FCKeditorAdaptor.FCKeditorDesigner") ]
    [ ParseChildren(false) ]
    public class FCKeditor : System.Web.UI.Control, IPostBackDataHandler
    {
        private bool _IsCompatible;

        public FCKeditor()
        {}

        #region Base Configurations Properties
       
        [ Browsable( false ) ]
        public FCKeditorConfigurations Config
        {
            get
            {
                if ( ViewState["Config"] == null )
                    ViewState["Config"] = new FCKeditorConfigurations() ;
                return (FCKeditorConfigurations)ViewState["Config"] ;
            }
        }

        [ DefaultValue( "" ) ]
        public string Value
        {
            get { object o = ViewState["Value"] ; return ( o == null ? "" : (string)o ) ; }
            set { ViewState["Value"] = value ; }
        }

        /// <summary>
        /// <p>
        ///        Sets or gets the virtual path to the editor's directory. It is
        ///        relative to the current page.
        /// </p>
        /// <p>
        ///        The default value is "/fckeditor/".
        /// </p>
        /// <p>
        ///        The base path can be also set in the Web.config file using the
        ///        appSettings section. Just set the "FCKeditor:BasePath" for that.
        ///        For example:
        ///        <code>
        ///        &lt;configuration&gt;
        ///            &lt;appSettings&gt;
        ///                &lt;add key="FCKeditor:BasePath" value="/scripts/fckeditor/" /&gt;
        ///            &lt;/appSettings&gt;
        ///        &lt;/configuration&gt;
        ///        </code>
        /// </p>
        /// </summary>
        [DefaultValue("/fckeditor/")]
        public string BasePath
        {
            get
            {
                object o = ViewState["BasePath"] ;

                if ( o == null )
                    o = System.Configuration.ConfigurationSettings.AppSettings["FCKeditor:BasePath"] ;

                return (o == null ? "/fckeditor/" : (string)o);
            }
            set { ViewState["BasePath"] = value ; }
        }

        [ DefaultValue( "Default" ) ]
        public string ToolbarSet
        {
            get { object o = ViewState["ToolbarSet"] ; return ( o == null ? "Default" : (string)o ) ; }
            set { ViewState["ToolbarSet"] = value ; }
        }

        #endregion

        #region Appearence Properties

        [ Category( "Appearence" ) ]
        [ DefaultValue( "100%" ) ]
        public Unit Width
        {
            get { object o = ViewState["Width"] ; return ( o == null ? Unit.Percentage(100) : (Unit)o ) ; }
            set { ViewState["Width"] = value ; }
        }

        [ Category("Appearence") ]
        [ DefaultValue( "200px" ) ]
        public Unit Height
        {
            get { object o = ViewState["Height"] ; return ( o == null ? Unit.Pixel( 200 ) : (Unit)o ) ; }
            set { ViewState["Height"] = value ; }
        }

        #endregion

        #region Configurations Properties

        [ Category("Configurations") ]
        public string CustomConfigurationsPath
        {
            set { this.Config["CustomConfigurationsPath"] = value ; }
        }

        [ Category("Configurations") ]
        public string EditorAreaCSS
        {
            set { this.Config["EditorAreaCSS"] = value ; }
        }

        [ Category("Configurations") ]
        public string BaseHref
        {
            set { this.Config["BaseHref"] = value ; }
        }

        [ Category("Configurations") ]
        public string SkinPath
        {
            set { this.Config["SkinPath"] = value ; }
        }

        [ Category("Configurations") ]
        public string PluginsPath
        {
            set { this.Config["PluginsPath"] = value ; }
        }

        [ Category("Configurations") ]
        public bool FullPage
        {
            set { this.Config["FullPage"] = ( value ? "true" : "false" ) ; }
        }

        [ Category("Configurations") ]
        public bool Debug
        {
            set { this.Config["Debug"] = ( value ? "true" : "false" ) ; }
        }

        [ Category("Configurations") ]
        public bool AutoDetectLanguage
        {
            set { this.Config["AutoDetectLanguage"] = ( value ? "true" : "false" ) ; }
        }

        [ Category("Configurations") ]
        public string DefaultLanguage
        {
            set { this.Config["DefaultLanguage"] = value ; }
        }

        [ Category("Configurations") ]
        public LanguageDirection ContentLangDirection
        {
            set { this.Config["ContentLangDirection"] = ( value == LanguageDirection.LeftToRight ? "ltr" : "rtl" )  ; }
        }

        [ Category("Configurations") ]
        public bool EnableXHTML
        {
            set { this.Config["EnableXHTML"] = ( value ? "true" : "false" ) ; }
        }

        [ Category("Configurations") ]
        public bool EnableSourceXHTML
        {
            set { this.Config["EnableSourceXHTML"] = ( value ? "true" : "false" ) ; }
        }

        [ Category("Configurations") ]
        public bool FillEmptyBlocks
        {
            set { this.Config["FillEmptyBlocks"] = ( value ? "true" : "false" ) ; }
        }

        [ Category("Configurations") ]
        public bool FormatSource
        {
            set { this.Config["FormatSource"] = ( value ? "true" : "false" ) ; }
        }

        [ Category("Configurations") ]
        public bool FormatOutput
        {
            set { this.Config["FormatOutput"] = ( value ? "true" : "false" ) ; }
        }

        [ Category("Configurations") ]
        public string FormatIndentator
        {
            set { this.Config["FormatIndentator"] = value ; }
        }

        [ Category("Configurations") ]
        public bool GeckoUseSPAN
        {
            set { this.Config["GeckoUseSPAN"] = ( value ? "true" : "false" ) ; }
        }

        [ Category("Configurations") ]
        public bool StartupFocus
        {
            set { this.Config["StartupFocus"] = ( value ? "true" : "false" ) ; }
        }

        [ Category("Configurations") ]
        public bool ForcePasteAsPlainText
        {
            set { this.Config["ForcePasteAsPlainText"] = ( value ? "true" : "false" ) ; }
        }

        [ Category("Configurations") ]
        public bool ForceSimpleAmpersand
        {
            set { this.Config["ForceSimpleAmpersand"] = ( value ? "true" : "false" ) ; }
        }

        [ Category("Configurations") ]
        public int TabSpaces
        {
            set { this.Config["TabSpaces"] = value.ToString( CultureInfo.InvariantCulture ) ; }
        }

        [ Category("Configurations") ]
        public bool UseBROnCarriageReturn
        {
            set { this.Config["UseBROnCarriageReturn"] = ( value ? "true" : "false" ) ; }
        }

        [ Category("Configurations") ]
        public bool ToolbarStartExpanded
        {
            set { this.Config["ToolbarStartExpanded"] = ( value ? "true" : "false" ) ; }
        }

        [ Category("Configurations") ]
        public bool ToolbarCanCollapse
        {
            set { this.Config["ToolbarCanCollapse"] = ( value ? "true" : "false" ) ; }
        }

        [ Category("Configurations") ]
        public string FontColors
        {
            set { this.Config["FontColors"] = value ; }
        }

        [ Category("Configurations") ]
        public string FontNames
        {
            set { this.Config["FontNames"] = value ; }
        }

        [ Category("Configurations") ]
        public string FontSizes
        {
            set { this.Config["FontSizes"] = value ; }
        }

        [ Category("Configurations") ]
        public string FontFormats
        {
            set { this.Config["FontFormats"] = value ; }
        }

        [ Category("Configurations") ]
        public string StylesXmlPath
        {
            set { this.Config["StylesXmlPath"] = value ; }
        }

        [ Category("Configurations") ]
        public string LinkBrowserURL
        {
            set { this.Config["LinkBrowserURL"] = value ; }
        }

        [ Category("Configurations") ]
        public string ImageBrowserURL
        {
            set { this.Config["ImageBrowserURL"] = value ; }
        }

        [Category("Configurations")]
        public bool HtmlEncodeOutput
        {
            set { this.Config["HtmlEncodeOutput"] = (value ? "true" : "false"); }
        }

        #endregion

        #region Rendering

        public string CreateHtml()
        {
            System.IO.StringWriter strWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter writer = new HtmlTextWriter(strWriter);
            this.Render(writer);
            return strWriter.ToString();
        }

        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write( "<div>" ) ;

            if (_IsCompatible)
            {
                string sLink = this.BasePath ;
                if ( sLink.StartsWith( "~" ) )
                    sLink = this.ResolveUrl( sLink ) ;

                string sFile =
                    System.Web.HttpContext.Current.Request.QueryString["fcksource"] == "true" ?
                        "fckeditor.original.html" :
                        "fckeditor.html" ;

                sLink += "editor/" + sFile + "?InstanceName=" + this.ClientID ;
                if ( this.ToolbarSet.Length > 0 ) sLink += "&amp;Toolbar=" + this.ToolbarSet ;

                // Render the linked hidden field.
                writer.Write(
                    "<input type=\"hidden\" id=\"{0}\" name=\"{1}\" value=\"{2}\" />",
                        this.ClientID,
                        this.UniqueID,
                        System.Web.HttpUtility.HtmlEncode( this.Value ) ) ;

                // Render the configurations hidden field.
                writer.Write(
                    "<input type=\"hidden\" id=\"{0}___Config\" value=\"{1}\" />",
                        this.ClientID,
                        this.Config.GetHiddenFieldString() ) ;

                // Render the editor IFRAME.
                writer.Write(
                    "<iframe id=\"{0}___Frame\" src=\"{1}\" class=\"fckeditorTextArea\" width=\"{2}\" height=\"{3}\" frameborder=\"no\" scrolling=\"no\"></iframe>",
                        this.ClientID,
                        sLink,
                        this.Width,
                        this.Height ) ;
            }
            else
            {
                writer.Write(
                    "<textarea name=\"{0}\" class=\"fckeditorTextArea\" rows=\"4\" cols=\"40\" style=\"width: {1}; height: {2}\" wrap=\"virtual\">{3}</textarea>",
                        this.UniqueID,
                        this.Width,
                        this.Height,
                        System.Web.HttpUtility.HtmlEncode( this.Value ) ) ;
            }

            writer.Write( "</div>" ) ;
        }

        protected override void OnPreRender( EventArgs e )
        {
            base.OnPreRender( e );
           
            _IsCompatible = this.CheckBrowserCompatibility();

            if ( !_IsCompatible )
                return;

            object oScriptManager = null;

            // Search for the ScriptManager control in the page.
            Control oParent = this.Parent;
            while ( oParent != null )
            {
                foreach ( object control in oParent.Controls )
                {
                    // Match by type name.
                    if ( control.GetType().FullName == "System.Web.UI.ScriptManager" )
                    {
                        oScriptManager = control;
                        break;
                    }
                }

                if ( oScriptManager != null )
                    break;

                oParent = oParent.Parent;
            }

            // If the ScriptManager control is available.
            if ( oScriptManager != null )
            {
                try
                {
                    // Use reflection to check the SupportsPartialRendering
                    // property value.
                    bool bSupportsPartialRendering = ((bool)(oScriptManager.GetType().GetProperty( "SupportsPartialRendering" ).GetValue( oScriptManager, null )));

                    if ( bSupportsPartialRendering )
                    {
                        string sScript = "(function()\n{\n" +
                            "\tvar editor = FCKeditorAPI.GetInstance('" + this.ClientID + "');\n" +
                            "\tif (editor)\n" +
                            "\t\teditor.UpdateLinkedField();\n" +
                            "})();\n";

                        // Call the RegisterOnSubmitStatement method through
                        // reflection.
                        oScriptManager.GetType().GetMethod( "RegisterOnSubmitStatement", new Type[] { typeof( Control ), typeof( Type ), typeof( String ), typeof( String ) } ).Invoke( oScriptManager, new object[] {
                            this,
                            this.GetType(),
                            "FCKeditorAjaxOnSubmit_" + this.ClientID,
                            sScript } );

                        // Tell the editor that we are handling the submit.
                        this.Config[ "PreventSubmitHandler" ] = "true";
                    }
                }
                catch { }
            }
        }

        #endregion

        #region Compatibility Check

        public bool CheckBrowserCompatibility()
        {
            return IsCompatibleBrowser();
        }

        /// <summary>
        /// Checks if the current HTTP request comes from a browser compatible
        /// with FCKeditor.
        /// </summary>
        /// <returns>"true" if the browser is compatible.</returns>
        public static bool IsCompatibleBrowser()
        {
            return IsCompatibleBrowser( System.Web.HttpContext.Current.Request );
        }

        /// <summary>
        /// Checks if the provided HttpRequest object comes from a browser
        /// compatible with FCKeditor.
        /// </summary>
        /// <returns>"true" if the browser is compatible.</returns>
        public static bool IsCompatibleBrowser( System.Web.HttpRequest request )
        {
            System.Web.HttpBrowserCapabilities oBrowser = request.Browser;

            // Internet Explorer 5.5+ for Windows
            if ( oBrowser.Browser == "IE" && ( oBrowser.MajorVersion >= 6 || ( oBrowser.MajorVersion == 5 && oBrowser.MinorVersion >= 0.5 ) ) && oBrowser.Win32 )
                return true;

            string sUserAgent = request.UserAgent;

            if ( sUserAgent.IndexOf( "Gecko/" ) >= 0 )
            {
                Match oMatch = Regex.Match( request.UserAgent, @"(?<=Gecko/)\d{8}" );
                return ( oMatch.Success && int.Parse( oMatch.Value, CultureInfo.InvariantCulture ) >= 20030210 );
            }

            if ( sUserAgent.IndexOf( "Opera/" ) >= 0 )
            {
                Match oMatch = Regex.Match( request.UserAgent, @"(?<=Opera/)[\d\.]+" );
                return ( oMatch.Success && float.Parse( oMatch.Value, CultureInfo.InvariantCulture ) >= 9.5 );
            }

            if ( sUserAgent.IndexOf( "AppleWebKit/" ) >= 0 )
            {
                Match oMatch = Regex.Match( request.UserAgent, @"(?<=AppleWebKit/)\d+" );
                return ( oMatch.Success && int.Parse( oMatch.Value, CultureInfo.InvariantCulture ) >= 522 );
            }

            return false;
        }

        #endregion

        #region Postback Handling

        public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {
            string postedValue = postCollection[postDataKey] ;

            // Revert the HtmlEncodeOutput changes.
            if ( this.Config["HtmlEncodeOutput"] != "false" )
            {
                postedValue = postedValue.Replace( "&lt;", "<" ) ;
                postedValue = postedValue.Replace( "&gt;", ">" ) ;
                postedValue = postedValue.Replace( "&amp;", "&" ) ;
            }

            if ( postedValue != this.Value )
            {
                this.Value = postedValue ;
                return true ;
            }
            return false ;
        }

        public void RaisePostDataChangedEvent()
        {
            // Do nothing
        }

        #endregion
    }
}