Showing posts with label Tips and Tricks. Show all posts
Showing posts with label Tips and Tricks. Show all posts

Tuesday, November 19, 2013

Push Notification for Android

Hello,

Now a Days in era of smart phones and mobile app developments, a very important feature is "Push Notification".

For any Mobile app (Android, iPhone, Blackberry, etc.) Push Notification is part of requirement and complete project.
To know more about Push notifications please Google !! here is a quick Wikipedia link.




In this post I am going to demonstrate Push notification for Android phones. As of now I don't have any Android device connected with my machine so can't get snapshots of result but one can trust me that whatever I have implemented is fully working.

OK.. So Let's Start ..........

  1.  Create an Asp.net application .(whatever you like..MVC, or anything) 

                       I hope you are aware about NuGet Package Manager. if not refer official website of NuGet. visual Studio 2010 + comes up with inbuilt support of NuGet Packages. still can't find NuGet Packages into your Visual Studio Install from Website.
  2. Once You are done with Above step, Right click on Solution of project. and Select "Manage NuGet Packages for Solution.."

  3. "Manage NuGet Package" window will appear. 
  4.  Thanks to "Redth", who has provided us a very useful NuGet Package Named "PushSharp"search from Right top search window for "PushSharp"  and Select the First Package.


  5. Click on "Install" Button. If Prompts to "Select Project", Select the Projects in which you would like to add reference of PushSharp library.Click OK.
  6. Here we go.. Nuget Package Installation will start and wait until is completes.


  7. Close all other open window. you can track output windows whether installation completed successfully. You can check in Project Reference, whether new references of PushSharp are assigned or not. If everything is good then let's move ahead Or feel free to post your problem. I will try my best to support you.

Now It's Time to create Project for Android Push Notification.

Please Follow the article to Create and Configure http://developer.android.com/google/gcm/gs.html (you might find some changes as recently Google has changed API Console UI. So try to push more efforts to understand)
Alright, I hope You have successfully Created Android API Project. It's very important part for Android push notification. 
You might have come across two important Key works while creating Project.
  1. Project Number : is used to generate Device Token from Android Device. The Project number keeps track of the notification raised for particular device consumes for which Project ID. You have to provide the Project number to Android phone developer. They will use the project number and Provide Device Token.


  2. API key : API key secured key mandatory to pass while processing notifications.



Keep this information somewhere stored.

Now There are three important credentials  required to accomplish Push notification for Android.
  1. Device Token : using Project Number, Android Phone developer can provide the Device Token. I have no Idea how they does.. 
  2. API Key : The API key provided by Project.
  3. Message: The message to be passed on as Push Notification.
Basically, Some implicit or explicit action required to raise the Notification. In My Case I used to created a WCF Restful service (Sample Application). We had a message with minor database parameters to be passed. So Whenever the notification was supposed to raise, phone developers were making a request on my WCF service with Device Token as Parameter.

Here is code block to raise notification. Very short and simple !! :)

var push = new PushBroker();            
push.RegisterGcmService(new GcmPushChannelSettings(APIKey));            
push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(DeviceTokenID)
                .WithJson("{\"message\":\"" + Message + "\"}")); 


That's all. Done..

I have done few more push notification also using PushSharp.
Please feel free to contact me for any kind of assistance.

Wednesday, August 21, 2013

Custom Message box and Confirm window all in one

Hello,
I have created a custom message box and confirm window which can be used in all programming languages and all platforms.
syntex :
AlertCust([Control], {Message Title}, [Message Text], {IconType}, {PromptType}, [OnOk], [OnCancel]);



Description :

  • [Control] : Optional, Pass the control which raises the prompt. in Confirm or Alert window when click ‘OK’ button is clicked, the default server event will be executed, if value is passed. if null, clicking on ‘OK’ the prompt window will be closed, no further action.
  • {Message Title} : Required, Message Title. Title will appear in bold font.
  • [Message Text] : Optional, Message text in second line, in normal fonts.
  • {IconType} : Required, Enum values. pass icon type to display icon specific to message. options Error, Warning, Information
  • {PromptType} : Required,  This property helps to decide what kind of prompt we need. e.g. Validation, MessageBox(OkOnly), OKCancel, YesNo.
  • [OnOk] : Optional, To provided custom callback method, set javascript method name, will be executed when clicked ‘OK’.
  • [OnCancel] : Optional, To provided custom callback method, set javascript method name, will be executed when clicked ‘Cancel’.





Message




anyone can download code from Here

Thursday, November 1, 2012

JavaScriptStringEncode : Javascript Compitable encoding

Hello,

Recently I was facing very interesting issue. and the solution for the issue was introduced in the new updates in asp.net framework 4.0.

Generally when we try to render HTML content on page clientside/ by javascript, it gives error of Potential dangerous content error.

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

There are lot's solutions but have to compromise security of page.
by setting

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="default.aspx.cs"
    Inherits="_default" ValidateRequest="false"%>


 But now we have perfect solution which is introduced in .net framework 4.0

HttpUtility.JavaScriptStringEncode Method


URL encoding makes sure that all browsers correctly encodes text in URL strings. Few Characters such as a question mark (?), ampersand (&), slash (/), and spaces might be truncated or corrupted by some browsers. Therefore, these characters must be encoded in a elements or in query strings where the strings can be re-sent by a browser in a request string.

refer following  MSDN link
http://msdn.microsoft.com/en-us/library/system.web.httputility.javascriptstringencode%28v=vs.100%29.aspx

http://msdn.microsoft.com/en-us/library/dd991914%28v=vs.100%29.aspx

Hope this helps

Tuesday, October 16, 2012

Disable Server Validation Control from ClientSide/ Javascript - ValidatorEnable

Hello Friends,

Recently I required to disable server validation control (RequiredFieldValidator, CompareValidator, CustomValidator, RangeValidator, RagularExpressionValidator, etc) from clientside/ Javascript.
There are few patches to accomplish the  requirement by I liked an approach which is perfect for ClientSide handling.

ValidatorEnable is a javascript mathod lying at asp.net framework javascriptscript

ValidatorEnable(document.getElementById(myVal), Status);

Thanks



Saturday, August 4, 2012

DateTime.ParseExact - culturewise Date Comparision

Hello..

Whenever dealing with cultures, DateTime format is always a headache to handle.

to the date format  in Textbox sometimes does not meet the format of culture.
in that case DateTime.ParseExact is good option to handle.

convert the date into current culture format from display culture format using

public static DateTime ParseExact( string str, string Dateformat, IFormatProvider provider)


Parameters

str
Type: System.String
A string that contains a date and time to convert.
Dateformat 
Type: System.String
A format specifier that defines the required format of s.
provider 
Type: System.IFormatProvider
An object that supplies culture-specific format information about s.
example
DateTime sessionDate = DateTime.ParseExact(txtDate.Text, "M-d-yyyy", provider);
here provide is
CultureInfo provider = CultureInfo.InvariantCulture;
this will get txtDate.Text (Date) into culture wise date format to compare with database formatted datetime.

Hope this Helps

All the best.


Tuesday, February 14, 2012

Handle Devide By Zero Error

Hi ..
set Arithaboth and Ansi_Warnings as OFF to handle devide by Zero or any kind of arithmatic errors

SET ARITHABORT OFF
SET ANSI_WARNINGS OFF
Declare @Denominator int =0
Declare @Numerator int =5
SELECT isnull(@Numerator / @Denominator,0) as Result


happy coding....

Saturday, January 7, 2012

Improve Performance by using OUTPUT in Insert Or Update Statement in single query

Hello friends,

recently I needed to fire a single SQL statement for Insert and Update and using the single statement I also needed to return the result of all Inserted/Updated Records details..

after searching a lot ... I came to know a very interesting way to perform both statement in single Query.

Generally for the scenario I got lots of suggestions to use Stored Procedure, but which was difficult for my scenario.

so I must get solution for it.

ok ok... let's come to point.

let's we have created a sample Table using the query

Create Table Table_1(Id Int Identity,Name nvarchar(100))


to insert records and get its generated Id
basically we perform like this

Insert into Table_1(Name) 
Select 'Sandeep'
Select @@IDENTITY


and same way for update
here the Updated value comes from other process which is not available Directly
[My case is only For Insert. but the concept we can use in Update also]

Declare @NewValue nvarchar(100)='Sandeep Prajapati'
Declare @ID int=1

Update Table_1
set Name=@NewValue
Where Id=@ID

select @ID as ID,@NewValue as Name


Now We can use OUTPUT key word to select the inserted/Updated Value to get affected rows in single query which also helps to improve performance.

Here is query for Insert

Insert Into Table_1(Name)
OutPut Inserted.Id,Inserted.Name
values('Sandeep')


after execution of the query the output is

 





Same way for Update

Update Table_1
set Name='Sandeep Prajapati'
OutPut inserted.ID,inserted.Name

Hope this helps...
Happy Coding...


Monday, January 2, 2012

Sample for WCF using json

Here is a sample for start WCF using json
in aspx page
  <script type="text/javascript">
        function ajaxService2() {
            serviceUrl = "http://localhost/WCFS/Service1.svc/GetData";
            var time = new Object();
            time.value = "1";
            $.ajax({
                type: "POST",
                url: serviceUrl,
                data: JSON.stringify(time),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (transport) {
                    var string = transport;
                    $("#<%= Text2.ClientID %>").val(string);
                },
                error: function (ex) {
                    alert("error" + ex.responseText);
                }
            });
        }

        function ajaxService1() {
            serviceUrl = "http://localhost/WCFS/Service1.svc/GetAllProducts";
            $.ajax({
                type: "GET",
                url: serviceUrl,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (transport) {
                    var string = transport;
                    $("#<%= Text1.ClientID %>").val(string);
                },
                error: function (ex) {
                    alert("error" + ex);
                }
            });
        }
    </script>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        <p>
            <input id="Button2" onclick="ajaxService1()" value="Ajax call service 1" type="button">
            <asp:textbox id="Text1" runat="server" />
        </p>
        <p>
            <input id="Button3" onclick="ajaxService2()" value="Ajax call service 2" type="button">
            <asp:textbox id="Text2" runat="server" />
        </p>
    

Web.config Settings for WCF and json in WCF’s Web.config
<?xml version="1.0"?>

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <system.serviceModel>
        <services>
            <service name="WCFS.Service1">
                <endpoint
                address="" binding="webHttpBinding"
                behaviorConfiguration="EndBehave"
                contract="WCFS.IService1"/>
            </service>
        </services>
        <behaviors>
            <endpointBehaviors>
                <behavior name="EndBehave">
                    <webHttp/>
                </behavior>
            </endpointBehaviors>
            <serviceBehaviors>
                <behavior>
                    <serviceMetadata httpGetEnabled="true"  />
                    <serviceDebug  includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
    </system.serviceModel>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
    </system.webServer>
</configuration>


in WCF Interface
 // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke( ResponseFormat = WebMessageFormat.Json, Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        [OperationContract]
        [WebInvoke(UriTemplate = "/GetAllProducts", ResponseFormat = WebMessageFormat.Json, Method = "GET")]
        List<product> GetAllProducts();
        // TODO: Add your service operations here
    }


    [DataContract]
    public class Product
    {
        [DataMember]
        public int ProdId { get; set; }
        [DataMember]
        public string PropName { get; set; }
        [DataMember]
        public int Quantity { get; set; }
        [DataMember]
        public int Price { get; set; }
    }

    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }

Service Class
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
    public class Service1 : IService1
    {
        public List<product> GetAllProducts()
        {
            return new List<product>
            {
                 new Product() {ProdId=101,PropName="Laptop",Quantity=200,Price=45000},
                 new Product() {ProdId=102,PropName="Desktop",Quantity=300,Price=35000},
            };
        }
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value.ToString());
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }

Happy Coding….

Thursday, December 15, 2011

Steps to Remove Menu options in Export for Report Page in SSRS

Hi,
In SSRS(Sql Server Reporting Service), I wanted to remove extra options to export my report.

Here are the steps to remove option to export like (word, Excel, PDF, MHTML etc...) in SSRS (Sql Server Reporting Service)

Installation folder may be different from MSSQL.1, can be MSSQL.x (search for rsreportserver.config under Program Files\Microsoft SQL Server if not found)
Here are the steps for Disabling Excel Export Option in Reporting Services -
  1. Go to Database server where reporting services is installed, open the rsreportserver.config file located at <Drive Letter>:\Program Files\Microsoft SQL Server\MSSQL.3\Reporting Services\ReportServer 
  2. Go to section.  
  3. Change this entry to i.e. add Visible="false" for Excel rendering extension 
  4. Same for PDF.  
Happy Reporting

Saturday, November 19, 2011

Create Excel File From DataTable

Hello Friends,
Many times we need to create Excel files in our application using existing Data.
I have figured out a class which will help to create excel file by just passing DataTable and preferred location to generate on server.
please download the cs file from here .. and use it :)

here is full code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;


    public class ExcelHelper
    {
        private static readonly ExcelHelper _instance = new ExcelHelper();

        public static ExcelHelper Instance
        {
            get { return _instance; }
        }
        /// <summary>
        /// Create one Excel-XML-Document with SpreadsheetML from a DataTable
        /// </summary>
        /// <param name="dataSource">Datasource which would be exported in Excel</param>
        /// <param name="fileName">Name of exported file</param>
        public void Create(DataTable dtSource, string strFileName)
        {
            // Create XMLWriter
            using (XmlTextWriter xtwWriter = new XmlTextWriter(strFileName, Encoding.UTF8))
            {

                //Format the output file for reading easier
                xtwWriter.Formatting = Formatting.Indented;

                // <?xml version="1.0"?>
                xtwWriter.WriteStartDocument();

                // <?mso-application progid="Excel.Sheet"?>
                xtwWriter.WriteProcessingInstruction("mso-application", "progid=\"Excel.Sheet\"");

                // <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet >"
                xtwWriter.WriteStartElement("Workbook", "urn:schemas-microsoft-com:office:spreadsheet");

                //Write definition of namespace
                xtwWriter.WriteAttributeString("xmlns", "o", null, "urn:schemas-microsoft-com:office:office");
                xtwWriter.WriteAttributeString("xmlns", "x", null, "urn:schemas-microsoft-com:office:excel");
                xtwWriter.WriteAttributeString("xmlns", "ss", null, "urn:schemas-microsoft-com:office:spreadsheet");
                xtwWriter.WriteAttributeString("xmlns", "html", null, "http://www.w3.org/TR/REC-html40");

                // <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
                xtwWriter.WriteStartElement("DocumentProperties", "urn:schemas-microsoft-com:office:office");

                // Write document properties
                xtwWriter.WriteElementString("Author", "Sandeep Prajapati");
                xtwWriter.WriteElementString("LastAuthor", "Sandeep Prajapati");
                xtwWriter.WriteElementString("Created", DateTime.Now.ToString("u") + "Z");
                xtwWriter.WriteElementString("Company", "XXXXXXXXXX");
                xtwWriter.WriteElementString("Version", "12");

                // </DocumentProperties>
                xtwWriter.WriteEndElement();

                // <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
                xtwWriter.WriteStartElement("ExcelWorkbook", "urn:schemas-microsoft-com:office:excel");

                // Write settings of workbook
                xtwWriter.WriteElementString("WindowHeight", "8010");
                xtwWriter.WriteElementString("WindowWidth", "14805");
                xtwWriter.WriteElementString("WindowTopX", "240");
                xtwWriter.WriteElementString("WindowTopY", "105");
                xtwWriter.WriteElementString("ProtectStructure", "False");
                xtwWriter.WriteElementString("ProtectWindows", "False");

                // </ExcelWorkbook>
                xtwWriter.WriteEndElement();

                // <Styles>
                xtwWriter.WriteStartElement("Styles");

                // <Style ss:ID="Default" ss:Name="Normal">
                xtwWriter.WriteStartElement("Style");
                xtwWriter.WriteAttributeString("ss", "ID", null, "Default");
                xtwWriter.WriteAttributeString("ss", "Name", null, "Normal");

                // <Alignment ss:Vertical="Bottom"/>
                xtwWriter.WriteStartElement("Alignment");
                xtwWriter.WriteAttributeString("ss", "Vertical", null, "Bottom");
                xtwWriter.WriteEndElement();

                // Write null on the other properties
                xtwWriter.WriteElementString("Borders", null);
                xtwWriter.WriteElementString("Font", null);
                xtwWriter.WriteElementString("Interior", null);
                xtwWriter.WriteElementString("NumberFormat", null);
                xtwWriter.WriteElementString("Protection", null);


                // </Style>
                xtwWriter.WriteEndElement();

                //<Style ss:ID="s16">
                xtwWriter.WriteStartElement("Style");
                xtwWriter.WriteAttributeString("ss", "ID", null, "s16");
                xtwWriter.WriteStartElement("Font");
                xtwWriter.WriteAttributeString("ss", "Bold", null, "1");
                xtwWriter.WriteAttributeString("ss", "Size", null, "11");
                xtwWriter.WriteAttributeString("ss", "Underline", null, "Single");
                xtwWriter.WriteEndElement();

                // </Style>
                xtwWriter.WriteEndElement();


                // </Styles>
                xtwWriter.WriteEndElement();

                // <Worksheet ss:Name="xxx">
                xtwWriter.WriteStartElement("Worksheet");
                xtwWriter.WriteAttributeString("ss", "Name", null, dtSource.TableName);

                // <Table ss:ExpandedColumnCount="2" ss:ExpandedRowCount="3" x:FullColumns="1" x:FullRows="1" ss:DefaultColumnWidth="60">
                xtwWriter.WriteStartElement("Table");
                xtwWriter.WriteAttributeString("ss", "ExpandedColumnCount", null, dtSource.Columns.Count.ToString());
                xtwWriter.WriteAttributeString("ss", "ExpandedRowCount", null, (dtSource.Rows.Count + 1).ToString());
                xtwWriter.WriteAttributeString("x", "FullColumns", null, "1");
                xtwWriter.WriteAttributeString("x", "FullRows", null, "1");
                //xtwWriter.WriteAttributeString("ss", "DefaultColumnWidth", null, "60");

                // Run through all rows of data source


                // <Row>
                xtwWriter.WriteStartElement("Row");
                foreach (DataColumn Header in dtSource.Columns)
                {
                    // <Cell>
                    xtwWriter.WriteStartElement("Cell");
                    xtwWriter.WriteAttributeString("ss", "StyleID", null, "s16");

                    // <Data ss:Type="String">xxx</Data>
                    xtwWriter.WriteStartElement("Data");
                    xtwWriter.WriteAttributeString("ss", "Type", null, "String");
                    // Write content of cell
                    xtwWriter.WriteValue(Header.ColumnName);

                    // </Data>
                    xtwWriter.WriteEndElement();

                    // </Cell>
                    xtwWriter.WriteEndElement();
                }

                xtwWriter.WriteEndElement();


                foreach (DataRow row in dtSource.Rows)
                {
                    // <Row>
                    xtwWriter.WriteStartElement("Row");

                    // Run through all cell of current rows
                    foreach (object cellValue in row.ItemArray)
                    {
                        // <Cell>
                        xtwWriter.WriteStartElement("Cell");
                        //if (cnt == 0)
                        //    xtwWriter.WriteAttributeString("ss", "StyleID", null, "s16");

                        // <Data ss:Type="String">xxx</Data>
                        xtwWriter.WriteStartElement("Data");
                        xtwWriter.WriteAttributeString("ss", "Type", null, "String");
                        // Write content of cell
                        string strcellValue = (cellValue == System.DBNull.Value ? string.Empty : (string)cellValue);
                        xtwWriter.WriteValue(strcellValue);

                        // </Data>
                        xtwWriter.WriteEndElement();

                        // </Cell>
                        xtwWriter.WriteEndElement();
                    }
                    // </Row>
                    xtwWriter.WriteEndElement();
                }
                // </Table>
                xtwWriter.WriteEndElement();

                // <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
                xtwWriter.WriteStartElement("WorksheetOptions", "urn:schemas-microsoft-com:office:excel");

                // Write settings of page
                xtwWriter.WriteStartElement("PageSetup");
                xtwWriter.WriteStartElement("Header");
                xtwWriter.WriteAttributeString("x", "Margin", null, "0.4921259845");
                xtwWriter.WriteEndElement();
                xtwWriter.WriteStartElement("Footer");
                xtwWriter.WriteAttributeString("x", "Margin", null, "0.4921259845");
                xtwWriter.WriteEndElement();
                xtwWriter.WriteStartElement("PageMargins");
                xtwWriter.WriteAttributeString("x", "Bottom", null, "0.984251969");
                xtwWriter.WriteAttributeString("x", "Left", null, "0.78740157499999996");
                xtwWriter.WriteAttributeString("x", "Right", null, "0.78740157499999996");
                xtwWriter.WriteAttributeString("x", "Top", null, "0.984251969");
                xtwWriter.WriteEndElement();
                xtwWriter.WriteEndElement();

                // <Selected/>
                xtwWriter.WriteElementString("Selected", null);

                // <Panes>
                xtwWriter.WriteStartElement("Panes");

                // <Pane>
                xtwWriter.WriteStartElement("Pane");

                // Write settings of active field
                xtwWriter.WriteElementString("Number", "1");
                xtwWriter.WriteElementString("ActiveRow", "1");
                xtwWriter.WriteElementString("ActiveCol", "1");

                // </Pane>
                xtwWriter.WriteEndElement();

                // </Panes>
                xtwWriter.WriteEndElement();

                // <ProtectObjects>False</ProtectObjects>
                xtwWriter.WriteElementString("ProtectObjects", "False");

                // <ProtectScenarios>False</ProtectScenarios>
                xtwWriter.WriteElementString("ProtectScenarios", "False");

                // </WorksheetOptions>
                xtwWriter.WriteEndElement();

                // </Worksheet>
                xtwWriter.WriteEndElement();

                // </Workbook>
                xtwWriter.WriteEndElement();

                // Write file on hard disk
                xtwWriter.Flush();
                xtwWriter.Close();
            }
        }
    }


Write me if help full
Happy Coding..

Friday, November 18, 2011

Scroll to particular record in GridView

Hello Friends,
here is a tip to scroll the gridview to particular record.
the basic concept is html scrolling. to scroll at particular position create an anchor tag with name as address (eg. #ScrollPoint '# is must')

now redirect the page to the location using javascript call
window.location.href = "#ScrollPoint";

 
same thing can be achieved by anchorlink href
here is sample code

HTML Page
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return MoveTo();" />
    <div style="height: 100px; overflow: auto;">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField HeaderText="ID" SortExpression="ID">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ID") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <a name='<%# Eval("ID") %>'></a>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            </Columns>
        </asp:GridView>
    </div>  


<script type="text/javascript">
        function MoveTo() {
            window.location.href = "#" + document.getElementById('<%= TextBox2.ClientID %>').value;
            return false;
        }
    </script>

Code Behind
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindControls();
            }
        }

        private void BindControls()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("Name");
            for (int i = 0; i < 200; i++)
            {
                AddRow(dt);    
            }


            GridView1.DataSource = dt;
            GridView1.DataBind();

        }

        private static void AddRow(DataTable dt)
        {
            DataRow dr = dt.NewRow();
            dr["ID"] = dt.Rows.Count + 1;
            dr["Name"] = "Sandeep" + dt.Rows.Count + 1;
            dt.Rows.Add(dr);
        }
    }
Happy Coding...

Wednesday, September 14, 2011

Power of common table expression (CTE)

Hello friends,
Recently I came across a case where I was supposed to generate report for Customer based on services availed to him and for that I used A common table expression (CTE) and it really impressed.
initially I referred this great document of MSDN http://msdn.microsoft.com/en-us/library/ms190766.aspx
here is my Table of data.(Actual Tables are not like this, I have managed a simplified Table for the Demo.)
Original Table Sandeep
Here is query to generate Table
declare @t table (id int identity,CustID int, AgreementName varchar(100), ServDate Datetime,Price float)
insert @t select 70       ,'First Agreement',CONVERT(datetime,'2011-01-05'),10
insert @t select 70       ,'Second Agreement',CONVERT(datetime,'2011-01-06'),10
insert @t select 75       ,'First Agreement',CONVERT(datetime,'2011-03-14'),10
insert @t select 70       ,'Second Agreement',CONVERT(datetime,'2011-01-05'),30
insert @t select 75       ,'Third Agreement',CONVERT(datetime,'2011-01-05'),10
insert @t select 90       ,'Third Agreement',CONVERT(datetime,'2011-04-16'),20
insert @t select 75       ,'Third Agreement',CONVERT(datetime,'2011-05-05'),10
insert @t select 90       ,'Third Agreement',CONVERT(datetime,'2011-02-20'),90
select * from @t





The scenario is to display Customer’s total bill based on the services availed to him according to Service Agreement and Date..

And Expect out put is as follow



Output Table Sandeep

For that I used the following query

;with cteTable(CustID,combined,inx,price)
as
(
select CustID,  AgreementName + ' ['+ CONVERT(varchar,ServDate,106)+']'                        
, inx=ROW_NUMBER() over (PARTITION by CustID order by AgreementName, ServDate),Price
from @t t
)
,cteConcate(CustID,finalstatus,inx,Price1)
as
(
select CustID, convert(varchar(max),combined), 1,(price) from cteTable where inx=1
union all
select cteConcate.CustID, convert(varchar(max),cteConcate.finalstatus+', '+cteTable.combined), cteConcate.inx+1, cteTable.price
from cteConcate
inner join cteTable on cteTable.CustID = cteConcate.CustID and cteTable.inx=cteConcate.inx+1

)
select CustID, MAX(finalstatus) Description ,sum(Price1) Price from cteConcate group by CustID






if have any query please let me know.



Happy Coding….

Friday, June 10, 2011

Access UserControl from Page


Hi..
To perform some reparative operation in application, its preferred to use UserControls.
Not necessary to have same display and bindings at everyplace. In that case we need to set values or call methods or pass values accordingly.
Here I have tried to figure out three cases, Hope it is helpful.
  1. Pass Table to Usercontrol and Set dynamically value to Controls
  2. Set Properties of control
  3. Call Usercontrol's Methods

Monday, June 6, 2011

Set Default Value as Function to column of a Table

Hello,
Generally we need to set default value to particular column in Database Table like isActive is true, IsDeleted is false.
same way many times we set CreatedOn Date as CurrentDate and that is by query of insert GetDate().
Static Values :
Its very easy to set some static value as Default value for column and that is as follow :
Static

Functions :
Set Default Date for Createdon Field as Follow :
Date
User Defined Functions :
Set User Defined function as Default Value as follow:
In my case I am supposed to get Random Hexa Code for Color. so I Have created an User Defined function for that
CREATE FUNCTION [dbo].[GetRandomColorCode]
( 
)
RETURNS varchar(6)
AS
BEGIN
Declare @Color varchar(6)
 RETURN (SELECT MyNewID FROM dbo.MyNewID)
END

Now set the function in columns as follow :

UserDefined



If this do not allow us to set Default value try following query to set

ALTER TABLE dbo.Table_1 ADD CONSTRAINT
 DF_Table_1_ColorCode DEFAULT ([dbo].[GetRandomColorCode]()) FOR ColorCode
GO

All the best



Happy Coding..

Thursday, May 26, 2011

Track Error in Javascript Page


Hi
Many times we have faced problems to find what is javascript errors and exactly where??
To track javascript error, It is a good practice to write code in Try..Catch
but sometimes some small syntax error are not allowing to execute the whole js file.
so to track such error during development, we can track by this sample code
  <script type="text/javascript">
        onerror = CallOnError;
        function CallOnError(msg, url, line) {
            var strErrMessage = "";
            strErrMessage += "Message: " + msg + "\n";
            strErrMessage += "Page: " + url + "\n";
            strErrMessage += "Line Number: " + line + "\n\n";
            alert(strErrMessage);
            return true;
        }
    </script>
  

Here is a sample error

try to put on your page

  <script type="text/javascript">
            alert('This is First Test Page);
    </script>

Enjoy Coding

Monday, May 16, 2011

Second Highest Salary- Sql Query


Create Table #Emp(id int identity primary key,
    Emp varchar(100),
    Salary int)

insert into #Emp
select 'XXXX',17000 union all
select 'DDDD',21000 union all
select 'WWWW',30000 union All
Select 'HHHH',21000 union All
select 'CCCC',30000 union All
Select 'TTTT',21000 union All
SElect 'PPPP',21000

select * from #Emp

select #Emp.* 
from (select ROW_NUMBER() over (order by salary desc) as RowNumber, Salary
   from #Emp
    group by Salary) as tempEmp inner join #Emp on tempEmp.Salary = #Emp.Salary
   where tempEmp.RowNumber=2

Drop Table #Emp

Data Will Look like this

Data

Output will be like this

Output

Friday, April 29, 2011

Protect image from being copied

Hello Friends,

Many times I am asked to protect some copyrighted images over web,
so finally I have found a better way to protect from being copied.
There are some cases by which we can copy the image
Here I have taken care of following cases
  • Right click on image and Save the Image
  • Save the Entire page and all images displayed on page will be downloaded to its Data Folder
  • in mozila Firefox, We can save the media files by following steps
    1. Right click on Page, select “View Page Info”
    2. ViewSourceSandeep
    3. It will open a window, Select “Media” tab, here a list of all files will be available
    4. select particular file and click on “Save As” button to save the media
    5. SavemediaSandeep


Now Let’s Start our main topic,that is protect image from being copied
There is a concept called Data URI scheme.
Generally to display any image on page, we use Relative_URL and if we display image using this, the images can be easily copied.
Here we will save image in database and retrieve the same
To Create table
CREATE TABLE [dbo].[Images](
 [ImageID] [int] IDENTITY(1,1) NOT NULL,
 [ImageName] [varchar](50) NULL,
 [Image] [image] NULL,
 [ext] [varchar](50) NULL,
 CONSTRAINT [PK_Images] PRIMARY KEY CLUSTERED 
(
 [ImageID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Now,

the aspx page will be very simple like


Wednesday, April 14, 2010

Light-weight Popup using CSS and Javascript..

Hello Friends
Once Again with a Rocking point we have seen lots of Popup till now…..
all are good at their places just search on Google “Model Popup” and you will get a long list of examples and javascripts for popup…
Ajax Control toolkit Model Popup Extender http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/ModalPopup/ModalPopup.aspx
 then few more
 http://www.modalpopups.com/blog/
http://www.jquery-dev.com/2008/12/02/jqmodal-jquery-modal-popup-plugin
one more javascript framework is Dojo http://www.dojotoolkit.org/
here i am also one type of popup… but i am sure you will like it
because it don’t require any kind of configuration and dependencies…

    

it is combination of CSS and javascript… with 70:30 ratio….
means here CSS is used more and rest is javascript….
then also its more power full

so from first sight you can determine its light–weight compare to other model popups

here i have an example…
   1: <input id="Button1" type="button"

   2:      value="Dispay Message" onclick="ShowDiv('DivPopUp')" />





Drop the control on which you want to fire ModelPopup.. and assign javascript event to fire onclick="ShowDiv('DivPopUp')"




if you are using server control like


   1: <asp:Button ID="Button2" runat="server" Text="Dispay Message" />



then at Server Side code….


in Page_Load Event


   1: Button2.Attributes.Add("onclick", "ShowDiv('DivPopUp')");



now

Friday, March 5, 2010

RemoteDataPass- pass data from one page to Remote Page

As i Committed in my previous post, that i will post code for ReportDataPass.

it is Quite difficult to pass Data from one Application to another application,
because here Cookie, Session variable will not help.
now a very simple way it Query string,  But as our previous condition, we don’t want to use Query string.
so the last way..
Post Method
as we know, in any server side scripting languages, like asp, jsp, PHP.. on submit button, the Data is posted to another page or to itself.
and using Request[“Filedname”]
we can have its Value. the same logic we are going to apply..
but as we are using VS, where we have facilities of Masterpages and Content page,so when we are using any ContentPage, in that case we can not have form and its Post method.

So we are going to make a dynamic Html Page, and  using dynamic Javascript we will post Data to another page.

So create a Class like this
   1: public class RemoteDataPass
   2: {
   3:     
   4:     private System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();
   5:     public string PostUrl = "";
   6:     public void Add(string FieldName, string Fieldvalue)
   7:     {
   8:         Inputs.Add(FieldName, Fieldvalue);
   9:     }
  10:  
  11:     public void Post()
  12:     {
  13:         System.Web.HttpContext.Current.Response.Clear();
  14:         System.Web.HttpContext.Current.Response.Write("<html><head></head><body onload=\"document.form1.submit()\">");
  15:         System.Web.HttpContext.Current.Response.Write(string.Format("<form name=\"form1\" method=\"post\" action=\"{0}\" >", PostUrl));
  16:         for (int i = 0; i < Inputs.Keys.Count; i++)
  17:         {
  18:             System.Web.HttpContext.Current.Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", Inputs.Keys[i], Inputs[Inputs.Keys[i]]));
  19:         }
  20:         System.Web.HttpContext.Current.Response.Write("</form></body></html>");        
  21:         System.Web.HttpContext.Current.Response.End();
  22:     }
  23: }








now to post Data from our Source Page.



   1: RemoteDataPass RemotePost = new RemoteDataPass();
   2:         RemotePost.PostUrl = "http://ransandeep.blogspot.com/test.aspx";
   3:         RemotePost.Add("FirstField", "Sandeep");        
   4:         RemotePost.Post(); 










now at Receiving page



   1: protected void Page_Load(object sender, EventArgs e)
   2:    {
   3:         if (Request.Form[ "FirstField" ] != null  )
   4:         {
   5:            Response.Write( "FirstField : "  + Request.Form[ "FirstField" ] +  "</br>" ) ;
   6:         }         
   7:    }







So this is Simple after getting know….





All the best..

Popup new Window by Javascript

A very Common trick
Open a new window as Popup by javascript…
Clicking on any Server Button

   1: <asp:Button ID="Button1" 
   2:                 runat="server" 
   3:                 OnClientClick="window.open('Page2.aspx',null,'height=200,width=400
   4:                         ,status=yes,toolbar=no,menubar=no,location=no,scroll=no');
   5:                         return false;"
   6:                 Text="Button" />







All The Best..