Thursday, 19 December 2013

WCF Interview Questions






1. What is WCF also known as?

  WCF (Windows Communication Foundation) is also know an  Indigo by its code name.

2. Difference between WCF and Web Services?

Below are the main differences between the WCF and Web Service:
Web Service:
1.    Can be hosted in IIS only
2.    Only two types of operations affects- One-Way, Request-Response
3.     To serialize the data use System.Xml.Serialization
4.    To encode the data use- XML 1.0, MTOM, DIME, Custom

WCF service:
1.    Can be hosted in IIS, Self Hosting, WAS, Windows Services etc
2.    Three types of operations affects- One-Way, Request-Response and Duplex
3.     To serialize the data use System.Runtimel.Serialization
4.    To encode the data use- XML 1.0, MTOM,Binary, Custom
5.    WCF Service can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P etc.

3. What are Endpoints?

 The collection of Address, Binding and Contract is called as End Point. In Sort,
EndPoint = A+B+C
Address (Where)-  it means where the service is hosted. URL of the service shows the address.
Binding (How)- How to connect to the service, is defined by the Binding. It basically has the definition of the communication channel to communicate to the WCF service
Contract (what)- It means what the service contains for the client. What all the methods are implemented in the WCF service is implemented in the Contract.

4. What are Behavior and Bindings?

Binding mainly describes about the communication of the client and service. For this, there are protocols corresponding to the binding behavior which will take care of the communication channel. There are different protocols which we use for the different types of bindings. E.g. HTTP, TCP, MSMQ, Named Pipes etc.
Behavior is used for the common configurations that could be for endpoints. When we use the common behavior, they affect to all the end points. Adding the service behavior affect the service related stuff while the endpoint related behavior affects the end points. Also operations level behavior affects the operations. 

5. What are different types of Contracts supported?

 There are mainly 5 type of contracts used in WCF service:
1. Service Contract
2. Operation Contract
3. Data Contract
4. Message Contract
5. Fault Contract

6. What is the difference between Transport and Message Security mode?

 WCF supports 2 types of security- Transport Level Security and Message Level Security
Transport Level Security- In this type of security, we make the transport channel as secure so that the data flows in that channel will be automatically secured. For HTTP channel, we use the client certificate for the security of the web address. SSL is used for the HTTP channel security. As we don’t need to secure each of the messages which are floating between the client and the service, the speed is faster as direct message is going to the client from the service.
Message level security- This type of security in WCF is used where we don’t have the fixed transport medium and we need to secure each message which is floating between the server and the client. In this type of security we use certain algorithms for making the message as secure message. We use some extra bits and send with the message. We also use some encryption techniques like SHA1 or MD5 which make the proper security for our message. As each message needs to be secured, this type of security makes some delay in the process of sending and receiving the messages.

7. How to configure WCF security to support Windows authentication?

To support the WCF security in Windows Authentication, we need to add the ClientCredetialType attribute to “Windows” under the security tab element:
transport clientCredentialType="Windows"

8. How to use Fault Contract?

 Fault Contract is mainly used for viewing and displaying the errors which occurred in the service. 
So it basically documents the error and the error message can be shown to the user in the understandable way.
We can’t use here the try….catch block for the error handling because the try…catch is the technology specific (.Net Technology). 
So we use the Fault contract for the error handling.

e.g. To use the Fault contract, we can simply write like the below:

public  int Add(int number1,int number2)
{
  // write some implementation
 throw new FaultException (“Error while adding data..”);
}

Here the fault Exception method is the inbuilt method which will throw the exception and display the message . We can use the custom class so that the message can be customized and the customized message can be sent to the client.

So we can creeat  a clss like:

Public Class CustomException()
{
public int ID{get;set;}
public string Message{get;set;}

public string Type{get;set;}
}

Now this custom type we ca use with the Operation Contract as:

[ServiceContract] 
Public interface IMyInterface
{
[OperationContract]
[FaultContract(typeOf(CustomException))]
Int Add(int num1,int num2);
}

Now while implementation of the Add method, we can assign the class properties.

Sunday, 8 December 2013

Setting Default theme for appbar in windows phone 7



  var phoneAccentBrush = new SolidColorBrush((App.Current.Resources["PhoneAccentBrush"] as SolidColorBrush).Color);
            this.ApplicationBar.BackgroundColor = Color.FromArgb(phoneAccentBrush.Color.A, phoneAccentBrush.Color.R, phoneAccentBrush.Color.G, phoneAccentBrush.Color.B);

Sunday, 1 December 2013

Improve Database Performance

To Improve Data Base Performance we should remember the following

1. Choose Appropriate Data Type
Choose appropriate SQL Data Type to store your data since it also helps in to improve the query performance. Example: To store strings use varchar in place of text data type since varchar performs better than text. Use text data type, whenever you required storing of large text data (more than 8000 characters). Up to 8000 characters data you can store in varchar.
2. Avoid nchar and nvarchar
Practice to avoid nchar and nvarchar data type since both the data types takes just double memory as char and varchar. Use nchar and nvarchar when you required to store Unicode (16-bit characters) data like as Hindi, Chinese characters etc.
3. Avoid NULL in fixed-length field
Practice to avoid the insertion of NULL values in the fixed-length (char) field. Since, NULL takes the same space as desired input value for that field. In case of requirement of NULL, use variable-length (varchar) field that takes less space for NULL.
4. Avoid * in SELECT statement
Practice to avoid * in Select statement since SQL Server converts the * to columns name before query execution. One more thing, instead of querying all columns by using * in select statement, give the name of columns which you required.
1. -- Avoid
2. SELECT * FROM tblName
3. --Best practice
4. SELECT col1,col2,col3 FROM tblName
5. Use EXISTS instead of IN
Practice to use EXISTS to check existence instead of IN since EXISTS is faster than IN.
1. -- Avoid
2. SELECT Name,Price FROM tblProduct
3. where ProductID IN (Select distinct ProductID from tblOrder)
4. --Best practice
5. SELECT Name,Price FROM tblProduct
6. where ProductID EXISTS (Select distinct ProductID from tblOrder)
6. Avoid Having Clause
Practice to avoid Having Clause since it acts as filter over selected rows. Having clause is required if you further wish to filter the result of an aggregations. Don't use HAVING clause for any other purpose.
7. Create Clustered and Non-Clustered Indexes
Practice to create clustered and non clustered index since indexes helps in to access data fastly. But be careful, more indexes on a tables will slow the INSERT,UPDATE,DELETE operations. Hence try to keep small no of indexes on a table.
8. Keep clustered index small
Practice to keep clustered index as much as possible since the fields used in clustered index may also used in nonclustered index and data in the database is also stored in the order of clustered index. Hence a large clustered index on a table with a large number of rows increase the size significantly. Please refer the article Effective Clustered Indexes
9. Avoid Cursors
Practice to avoid cursor since cursor are very slow in performance. Always try to use SQL Server cursor alternative. Please refer the article Cursor Alternative.
10. Use Table variable inplace of Temp table
Practice to use Table varible in place of Temp table since Temp table resides in the TempDb database. Hence use of Temp tables required interaction with TempDb database that is a little bit time taking task.
11. Use UNION ALL inplace of UNION
Practice to use UNION ALL in place of UNION since it is faster than UNION as it doesn't sort the result set for distinguished values.
12. Use Schema name before SQL objects name
Practice to use schema name before SQL object name followed by "." since it helps the SQL Server for finding that object in a specific schema. As a result performance is best.
1. --Here dbo is schema name
2. SELECT col1,col2 from dbo.tblName
3. -- Avoid
4. SELECT col1,col2 from tblName
13. Keep Transaction small
Practice to keep transaction as small as possible since transaction lock the processing tables data during its life. Some times long transaction may results into deadlocks. Please refer the article SQL Server Transactions Management
14. SET NOCOUNT ON
Practice to set NOCOUNT ON since SQL Server returns number of rows effected by SELECT,INSERT,UPDATE and DELETE statement. We can stop this by setting NOCOUNT ON like as:
1. CREATE PROCEDURE dbo.MyTestProc
2. AS
3. SET NOCOUNT ON
4. BEGIN
5. .
6. .
7. END
15. Use TRY-Catch
Practice to use TRY-CATCH for handling errors in T-SQL statements. Sometimes an error in a running transaction may cause deadlock if you have no handle error by using TRY-CATCH. Please refer the article Exception Handling by TRY…CATCH
16. Use Stored Procedure for frequently used data and more complex queries
Practice to create stored procedure for quaery that is required to access data frequently. We also created stored procedure for resolving more complex task.
17. Avoid prefix "sp_" with user defined stored procedure name
Practice to avoid prefix "sp_" with user defined stored procedure name since system defined stored procedure name starts with prefix "sp_". Hence SQL server first search the user defined procedure in the master database and after that in the current session database. This is time consuming and may give unexcepted result if system defined stored procedure have the same name as your defined procedure.

Monday, 4 November 2013

image file validating using jquery in asp.net


<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js" type="text/javascript"></script>
<script src="htp://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $('#<%=FileUpload1.ClientID %>').change(function () {
            var ValidFileExtension = ['jpg', 'JPG', 'jpeg', 'JPEG', 'png', 'PNG', 'gif', 'GIF', 'bmp', 'BMP'];
        if ($.inArray($(this).val().split('.').pop().toLowerCase(), ValidFileExtension) == -1) {
            alert("Sorry !!! Allowed image formats are '.jpeg','.jpg', '.png', '.gif', '.bmp'");
        }
    });
});
</script>


    <table>
                <tr>
                    <td colspan="2"><asp:FileUpload ID="FileUpload1" runat="server" /></td>                  
                </tr>
                <tr>
                    <td><asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" /></td>
                    <td>
                        <asp:Label ID="lblStatus" runat="server" Text=""></asp:Label></td>
                </tr>            
            </table>  


protected void btnUpload_Click(object sender, EventArgs e)
    {
        string filePath = string.Empty;
        try
        {
            filePath = (Server.MapPath("Images/") + Guid.NewGuid() + FileUpload1.FileName);
            FileUpload1.SaveAs(filePath);
            lblStatus.Text = "Image uploaded successfully";
            lblStatus.ForeColor = System.Drawing.Color.Green;
        }
        catch (Exception ex)
        {
            lblStatus.Text = "Image couldn't be uploaded";
            lblStatus.ForeColor = System.Drawing.Color.Red;        
        }
        finally
        {
            filePath = string.Empty;
        }    
    }

Sunday, 3 November 2013

How to validate checkbox before save data

<script type="text/javascript" language="javascript">


   // This function is used for validatecheckbox

    function ValidateCheckBox() {
        var chekbox = document.getElementById('<%=chkterms.ClientID %>');
        var spanelement = document.getElementById('Span1')
        if (chekbox.checked == true) {
            spanelement.style.display = 'none';
        } else {
            spanelement.style.display = '';
            return false;
        }
    }    
</script>


  <tr>
  <td align="left" colspan="2">
            <asp:CheckBox ID="chkterms" runat="server" onchange="javascript:ValidateCheckBox();" />
            <strong style="font: bold 16px 'Century Gothic'"><a href="../Terms.aspx" target="_blank">
                <u>I Agree Terms and Conditions</u></a></strong>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <span id="Span1" style="color: red; display: none;">You must and should Agree the Terms
                and Conditions </span>
        </td>
    </tr>


   <tr>
        <td>
            <ul class="pager wizard">
                <li class="back">
                    <asp:LinkButton ID="Btn2" runat="server" OnClick="Btn2_Click">Previous</asp:LinkButton>
                </li>
            </ul>
        </td>
        <td>
            <ul class="pager wizard">
                <li class="back">
                    <asp:LinkButton ID="btnsave" runat="server" ValidationGroup="regroup" OnClientClick="javascript:return ValidateCheckBox();"
                        OnClick="btnsave_Click">Save</asp:LinkButton>
                </li>
            </ul>
        </td>
    </tr>

  protected void btnsave_Click(object sender, EventArgs e)
    {
 Response.Redirect("AccountPreview.aspx",false);
}


Saturday, 2 November 2013

maximum length validation of multilinetextbox in asp.net


solution1:

Using Javascript in asp.net

function Count(text,long)

{

      var maxlength = new Number(long);

if(document.getElementById('<%=textBox.ClientID%>').value.length > maxlength){

            text.value = text.value.substring(0,maxlength);

            alert(" Only " + long + " chars");
}

Your textbox code should look like

<asp:TextBox ID="textBox" onKeyUp="javascript:Count(this,200);" onChange="javascript:Count(this,200);"  TextMode=MultiLine Columns="5" Rows="5" runat=server>
    </asp:TextBox>


solution2:

using regularexpression in asp.net

<asp:RegularExpressionValidator ID="txtConclusionValidator1" ControlToValidate="textBox" Text="Exceeding 200 characters" ValidationExpression="^[\s\S]{0,2}$" runat="server" />

<asp:TextBox ID="textBox" TextMode=MultiLine Columns="5" Rows="5" runat=server></asp:TextBox>


solution3:

using jqury in asp.net

$(document).ready(function () {
        var maxLength = 150;
        var txt = $('#<%=lbladdress.ClientID%>');
        txt.html('');
        $('#<%=txt_HoAddress.ClientID%>').keyup(function () {
            var text = $(this).val();
            if (text != "") {
                var textLength = text.length;
                if (textLength > maxLength) {
                    $(this).val(text.substring(0, (maxLength)));
                    txt.html("Sorry, you only " + maxLength + " characters are allowed");
                    text.focus();
                }
            }
            else {
                txt.html("Please Enter the Address");
            }
        });
    });

or

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script type="text/javascript">
   $(function () {
            var limit = 50;
            $("textarea[id$=txtAddress]").keyup(function () {
                var len = $(this).val().length;
                if (len > limit) {
                    this.value = this.value.substring(0, limit);
                }
                $('#spn').text(limit - len + " characters left");
            });
        });
    </script>

 <asp:TextBox ID="txtAddress" runat="server" TextMode="MultiLine"></asp:TextBox>
                    <span id="spn"></span>

jQuery used in asp.net forms

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
        </script>

    <script type="text/javascript">
 

    $(document).ready(function() {

        // put all your jQuery goodness in here.

    });


    </script>

age must be greaterthan 18 based on dtaeofbirth condition checking in javascript












cheking age in javascript


 // This fuction is used for age checking

    function checkage() {
        var lblage = document.getElementById('<%=lblage.ClientID %>');
        lblage.innerHTML = '';
        var todaydate = $get('<%= hftodaydate.ClientID %>').value;
        var birthdate = document.getElementById('<%=txtdob.ClientID %>');
        if (todaydate != '' && birthdate != '') {
            var d1 = todaydate.split("/");
            var d2 = birthdate.value.split("/");
            var tdate = new Date(d1[2], d1[1] - 1, d1[0]);
            var bdate = new Date(d2[2], d2[1] - 1, d2[0]);
            if (bdate < tdate) {
                var currentyear = tdate.getFullYear();
                var birthyear = bdate.getFullYear();
                var age = parseInt(currentyear) - parseInt(birthyear);
                if (parseInt(age) < 18) {
                    lblage.innerHTML = 'Age Is Must be Greaterthan 18';
                    birthdate.value = '';
                    birthdate.focus();
                }
            }
            else {
                lblage.innerHTML = 'Age Is Must be Greaterthan 18';
            }
        }
        else {
            lblage.innerHTML = 'Enter DateOfBirth';
        }
    }


your asp.x code

<asp:TextBox ID="txtdob" MaxLength="15" runat="server" CssClass="reform-input" onchange="checkage();"></asp:TextBox>
            <ajaxToolkit:FilteredTextBoxExtender ID="FTBEtxtactivationdate" runat="server" TargetControlID="txtdob"
                FilterType="Custom" ValidChars="0123456789/" FilterMode="ValidChars">
            </ajaxToolkit:FilteredTextBoxExtender>
            <ajaxToolkit:CalendarExtender ID="CEtxtactivationdate" runat="server" TargetControlID="txtdob"
                BehaviorID="CEtxtactivationdate" Format="dd/MM/yyyy">
            </ajaxToolkit:CalendarExtender>
            <asp:RequiredFieldValidator ID="RFVtxtdob" runat="server" ErrorMessage="Enter DOB"
                SetFocusOnError="true" Display="None" ValidationGroup="account" ControlToValidate="txtdob"></asp:RequiredFieldValidator>
            <ajaxToolkit:ValidatorCalloutExtender ID="VCEtxtdob" runat="server" TargetControlID="RFVtxtdob">
            </ajaxToolkit:ValidatorCalloutExtender>
            <asp:RegularExpressionValidator ID="rgeDob" runat="server" ControlToValidate="txtdob"
                SetFocusOnError="True" ErrorMessage="Please enter dob in dd/mm/yyyy format" ValidationExpression="^(((0[1-9]|[12]\d|3[01])/(0[13578]|1[02])/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)/(0[13456789]|1[012])/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])/02/((19|[2-9]\d)\d{2}))|(29/02/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$"
                Display="None"></asp:RegularExpressionValidator>
            <ajaxToolkit:ValidatorCalloutExtender ID="VCE1_txtdob" runat="server" TargetControlID="rgeDob">
            </ajaxToolkit:ValidatorCalloutExtender>
            <asp:Label ID="lblage" runat="server" ForeColor="Red"></asp:Label>

Friday, 19 July 2013

GETUTCDATE() function in sqlserver



--UTC Time
SELECT 'UTC Time' as 'TimeZone','UTC' as 'TimeAbb' ,CONVERT(varchar(20),GETUTCDATE(),113) as 'Current Time'
UNION ALL

--IST Time i.e. India Time=UTC+5:30
SELECT 'India Time' as 'TimeZone','IST' as 'TimeAbb',CONVERT(varchar(20),DATEADD(MI,30,DATEADD(hh,5,GETUTCDATE())),113) as 'Current Time'
UNION ALL

-- Atlantic Time = UTC-4
SELECT 'Atlantic Time' as 'TimeZone','ATS' as 'TimeAbb',CONVERT(varchar(20),DATEADD(hh,-4,GETUTCDATE()),113) as 'Current Time'
UNION ALL

-- Eastern Time = UTC-5
SELECT 'Eastern Time' as 'TimeZone','ETS' as 'TimeAbb',CONVERT(varchar(20),DATEADD(hh,-5,GETUTCDATE()),113) as 'Current Time'
UNION ALL

-- Mountain Time = UTC-6
SELECT 'Mountain Time' as 'TimeZone','MTS' as 'TimeAbb',CONVERT(varchar(20),DATEADD(hh,-6,GETUTCDATE()),113) as 'Current Time'
UNION ALL

-- Pacific Time = UTC-8
SELECT 'Pacific Time' as 'TimeZone','PST' as 'TimeAbb',CONVERT(varchar(20),DATEADD(hh,-8,GETUTCDATE()),113) as 'Current Time'
UNION ALL

-- Alaska Time = UTC-9
SELECT 'Alaska Time' as 'TimeZone','AKST' as 'TimeAbb',CONVERT(varchar(20),DATEADD(hh,-9,GETUTCDATE()),113) as 'Current Time'
UNION ALL

-- Hawai Time = UTC-10
SELECT 'Hawai Time' as 'TimeZone','HST' as 'TimeAbb',CONVERT(varchar(20),DATEADD(hh,-10,GETUTCDATE()),113) as 'Current Time'

Wednesday, 17 July 2013

PdfDocument code in c#

C#:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Drawing.Printing;

using Spire.Pdf;

namespace PdfPrint

{

class Program

{

[STAThread()]

static void Main(string[] args)

{

// Instantiate an object of PdfDocument

PdfDocument doc = new PdfDocument();

string pdfFile = “sample.pdf”;

//load PDF document

doc.LoadFromFile(pdfFile);

//Default printing mode without interaction (default printer to print all pages of the document)

doc.PrintDocument.Print();

//Interaction printing mode(page range,printer,and properties of printing can be freely to selected and set)

PrintDialog dialogPrint = new PrintDialog();

dialogPrint.AllowPrintToFile = true;

dialogPrint.AllowSomePages = true;

dialogPrint.PrinterSettings.MinimumPage = 1;

dialogPrint.PrinterSettings.MaximumPage = doc.Pages.Count;

dialogPrint.PrinterSettings.FromPage = 1;

dialogPrint.PrinterSettings.ToPage = doc.Pages.Count;

if (dialogPrint.ShowDialog() == DialogResult.OK)

{

//the startpage was selected to be printed

doc.PrintFromPage = dialogPrint.PrinterSettings.FromPage;

//the endpage was selected to be printed

doc.PrintToPage = dialogPrint.PrinterSettings.ToPage;

//Choose printer to print pdf document

doc.PrinterName = dialogPrint.PrinterSettings.PrinterName;

PrintDocument printDoc = doc.PrintDocument;

dialogPrint.Document = printDoc;

//Realize printing

printDoc.Print();

}

}

}

}


Tuesday, 16 July 2013

Calculate age on date selection using Javascript

<script type="text/javascript">
        function DateSelectionChanged(e) {
            var today = new Date();
            var dob = e.get_selectedDate();
            var months = (today.getMonth() - dob.getMonth() + (12 * (today.getFullYear() - dob.getFullYear())));
            //alert("Your age: " + Math.round(months / 12));
            var age = Math.round(months / 12);
            if (age < 16) {
                alert("Error Age is less than 16");
            }
        }  
    </script>

<asp:TextBox ID="txtDate" runat="server" />
        <asp:ImageButton runat="server" ID="imgPopup" ImageUrl="~/Images/Calendar.png" />
        <ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" OnClientDateSelectionChanged="DateSelectionChanged"
            TargetControlID="txtDate" PopupButtonID="imgPopup">
        </ajaxToolkit:CalendarExtender>

Wednesday, 26 June 2013

Difference Between STUFF() and Replace() in SqlServer



1. STUFF()

This function can be used for delete a certain length of the string and insert a new string in the deleted place.

Syntax

Code:
STUFF ( InputString, start, length, ReplacedString )

STUFF (String, StartPos, LengthofReplaceChar, ReplaceString)

String - String to be overwritten
StartPos - Starting Position for overwriting
LengthofReplaceChar - Length of replacement string
ReplaceString - String to overwrite


Example

Code:

Select STUFF ("this is a test", 7, 2, "was")

-- Result - this was a test


2. REPLACE()

This function replaces all the occurrences of a string expression with a new string within an input string.

Syntax:

Code:
REPLACE ( InputString , StringToReplace , NewString )

REPLACE (String, StringToReplace,StringTobeReplaced)

String - Input String
StringToReplace - The portion of string to replace
StringTobeReplaced - String to overwrite



Example,


Code:
Select REPLACE ("This is a test and it is successful!","is","was")

 Result :
This was a test and it was successful!

EX:

Both STUFF and REPLACE are used to replace characters in a string.

select replace('abcdef','ab','xx')
Result:   xxcdef
select replace('defdefdef','def','abc')
Result :   abcabcabc
We cannot replace a specific occurrence of "def" using REPLACE.

select stuff('defdefdef',4, 3,'abc')
Result:  defabcdef

where 4 is the character to begin replace from and 3 is the number of characters to replace.

Tuesday, 25 June 2013

sqlserver interview questions


1.What is difference between Clustered and Non Clustered index?

There are two Types of Index available in Sql Server:

1) Clustered Index
2) Non Clustered Index

Index is used for increase the performance application.
1) Clustered Index sequential order .primary key default clustered index. each table only once clustered index.

2) unique key default non clustered index. There 256 non clustered index in each table.


2.how to find duplicates in a table in sql server?

This query demonstrates usage of GROUP BY, HAVING, ORDER BY in one query and returns the results with duplicate column and its count in descending order.

SELECT YourColumn, COUNT(*) TotalCount
FROM YourTable
GROUP BY YourColumn
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC







yield keyword in c#


With yield keyword, the control moves from the caller to source and from the source back to the caller to and fro.

yield statement can be used in two forms

yield return <expression>;
yield break;

yield return statement returns each element at at time.
Yield return allows you to run custom iteration without temp collection.

Lets take an example to understand in more detail

Function to return RandomNumbers using List

static IEnumerable<int> GetRandomNumbers(int count)
{
    Random rand = new Random();
    List<int> ints = new List<int>(count);
    for (int i = 0; i < count; i++)
    {
        ints.Add(rand.Next());
    }
    return ints;
}

Same function using return yield without using any temp collection

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (int i in GetRandomNumbers(10))
                Console.WriteLine(i);
        }      

        static IEnumerable<int> GetRandomNumbers(int count)
        {
            Random rand = new Random();          
            for (int i = 0; i < count; i++)
            {
                yield return rand.Next();
            }          
        }
    }
}
OUTPUT:

1191885058
2054102666
1386021465
1841172832
1017760911
2105028861
549081689
1595410548
585549736
381274724

See, in the above examples, both are performing the same thing, but in the first example we are creating temp collection "list" but in the second example with yield there is no need create any temp collection

yield break statement is used to break the iteration. break statement is used to terminate the loop but yield break is used to return from the method.

static void Main(string[] args)
{          
    foreach (int i in GetRandomNumbers(10))
        Console.WriteLine(i);
    System.Threading.Thread.Sleep(5000);          
}

static IEnumerable<int> GetRandomNumbers(int count)
{
    Random rand = new Random();
    for (int i = 0; i < count; i++)
    {
        yield return rand.Next();
        yield break;
    }
}
OUTPUT:

41820105

Monday, 24 June 2013

Datalist Paging in asp.net

<table>              
        <tr>
            <td>
           
            <div class="youtube_thumb_handler1">
                <asp:DataList ID="DLVideos" runat="server" RepeatColumns="3" RepeatDirection="Horizontal"
                    CellPadding="0" CellSpacing="0">
                    <ItemTemplate>                                    
                          <iframe id="iframe_Trailer" runat="server" scrolling="no" marginwidth="0" marginheight="0"
                           src='<%#Eval("VideoURL") %>' height="100" width="150" frameborder="0"></iframe>
                         
                              <div class="youtube_thumb_title1"> <a id="A1" href='<%#Eval("Sno","videoDetails.aspx?sno={0}") %>' runat="server">
                                        <%#Eval("Title")%></a> </div>
                       
                       
                    </ItemTemplate>
                </asp:DataList>
                </div>
               
                <table align="center">
                        <tr>
                            <td>
                            <br />

                                <asp:Label ID="lblCurrentPage" runat="server" Visible="true" CssClass="y_pagetext"></asp:Label>
                                <asp:Button ID="cmdPrev" runat="server" CssClass="y_next" Text=" Previous " OnClick="cmdPrev_Click" />&nbsp;&nbsp;&nbsp;
                                <asp:Button ID="cmdNext" runat="server" CssClass="y_next" Text=" Next " OnClick="cmdNext_Click" />
                            </td>
                        </tr>
               </table>                          
            </td>
        </tr>      
    </table>



  protected void Page_Load(object sender, EventArgs e)
    {
        BindVideos();
    }
    protected void BindVideos()
    {
        try
        {
            ds = objbll.Get_Related_Content("AllVideos", "");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                PagedDataSource PagedData = new PagedDataSource();
                dv = ds.Tables[0].DefaultView;
                PagedData.DataSource = dv;
                PagedData.AllowPaging = true;
                PagedData.PageSize = 12;

                PagedData.CurrentPageIndex = CurrentPage;
                lblCurrentPage.Text = "Page:" + (CurrentPage + 1).ToString() + " Of " + PagedData.PageCount.ToString();
                cmdPrev.Enabled = !PagedData.IsFirstPage;
                cmdNext.Enabled = !PagedData.IsLastPage;

                DLVideos.DataSource = PagedData;
                DLVideos.DataBind();
            }
            else
            {
                DLVideos.DataSource = null;
                dv = null;
                DLVideos.DataBind();
            }
        }
        catch
        {
        }
    }
    public int CurrentPage
    {

        get
        {
            object o = this.ViewState["_CurrentPage"];

            if (o == null)

                return 0;
            else

                return (int)o;
        }

        set
        {
            this.ViewState["_CurrentPage"] = value;

        }
    }
    protected void cmdPrev_Click(object sender, EventArgs e)
    {
        try
        {
            CurrentPage -= 1;
            BindVideos();
        }
        catch
        {

        }
    }
    protected void cmdNext_Click(object sender, EventArgs e)
    {
        try
        {
            CurrentPage += 1;

            BindVideos();
        }
        catch
        {

        }
    }

Ajax ToggleButtonExtender used in gridview in asp.net

<asp:TemplateField HeaderText="Status" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
                                    <center>
                                        <asp:CheckBox ID="chkboxStatus" Checked='<%# Convert.ToBoolean(Eval("Status").ToString())%>'
                                            runat="server" AutoPostBack="true" OnCheckedChanged="chkboxStatus_CheckedChanged" />
                                        <br />
                                        <ajaxToolkit:ToggleButtonExtender ID="ToggleButtonExtender1" runat="server" TargetControlID="chkboxStatus"
                                            ImageWidth="50" ImageHeight="50" UncheckedImageUrl="~/images/unchecked.jpg" CheckedImageUrl="~/images/tick.png"
                                            CheckedImageAlternateText="Check" UncheckedImageAlternateText="UnCheck">
                                        </ajaxToolkit:ToggleButtonExtender>
                                    </center>
                                </ItemTemplate>
                            </asp:TemplateField>


protected void chkboxStatus_CheckedChanged(object sender, EventArgs e)
    {
        GridViewRow gvrow;
        gvrow = ((CheckBox)sender).Parent.Parent as GridViewRow;
        int gindex = gvrow.RowIndex;
        Label lblHeadLineID = (Label)gridNews.Rows[gindex].FindControl("lblHeadLineID");
        CheckBox chkboxStatus = (CheckBox)gridNews.Rows[gindex].FindControl("chkboxStatus");
        string news_status = null;

        if (chkboxStatus.Checked)
        {
            news_status = "True";
        }
        else
        {
            news_status = "False";
        }

        objbll.Update_News_status(lblHeadLineID.Text, news_status);

    }

Friday, 21 June 2013

Check EmailID Already exists or not in asp.net


<script language="javascript" type="text/javascript">

    function checkuserEmail(txt) {
        var valuseremail = txt;
        if (valuseremail != "") {

            WebService.check_ContentEditor_userEmail(valuseremail, OnSucceeded, OnFailed);
        }

    }
    function OnSucceeded(result, userContext, methodName) {

        var userarray = result;
        document.getElementById('<%=lblresult.ClientID %>').innerHTML = userarray;
        if (userarray != "<font color='green'>EmaiID Available,Please proceed !</font>") {
            document.getElementById('<%=txtEmail.ClientID %>').value = "";
        }


    }
    function OnFailed(error, userContext, methodName) {

        alert("An Error Occured During Check Your EmailID. Please Try After Some Time!!!");
    }

</script>


<asp:TextBox ID="txtEmail" runat="server" CssClass="serachtext1" onblur="checkuserEmail(this.value);"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RFV_txtEmail" runat="server" ControlToValidate="txtEmail"
                    Display="None" SetFocusOnError="true" ErrorMessage="Enter EmailID" ValidationGroup="Insert"></asp:RequiredFieldValidator>
                <ajaxToolkit:ValidatorCalloutExtender ID="VCE3_txtEmail" CssClass="customCalloutStyle"
                    runat="server" WarningIconImageUrl="~/images/ajaxerror.png" CloseImageUrl="~/images/ajaxclose.png"
                    TargetControlID="RFV_txtEmail">
                </ajaxToolkit:ValidatorCalloutExtender>
                <asp:RegularExpressionValidator ID="REV_txtEmail" runat="server" ControlToValidate="txtEmail"
                    Display="None" SetFocusOnError="true" ErrorMessage="Enter valid EmailID" ValidationGroup="Insert"
                    ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
                <ajaxToolkit:ValidatorCalloutExtender ID="VCE2_txtEmail" CssClass="customCalloutStyle"
                    runat="server" WarningIconImageUrl="~/images/ajaxerror.png" CloseImageUrl="~/images/ajaxclose.png"
                    TargetControlID="REV_txtEmail">
                </ajaxToolkit:ValidatorCalloutExtender>
                <asp:Label ID="lblresult" runat="server" Font-Bold="False" ForeColor="Red" Text=""></asp:Label>

[WebMethod]
    public string check_ContentEditor_userEmail(string emailid)
    {
        try
        {
            BAL.TravelBAL objtravelbal = new BAL.TravelBAL();  
            DataSet ds = new DataSet();
            ds = objtravelbal.Get_CityContentEditor_ByEmail(emailid);
            string result = "";
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                result = "<font color='red'>EmaiID Already Exist,Please Enter Another EmailID!</font>";
            }
            else
            {
                result = "<font color='green'>EmaiID Available,Please proceed !</font>";
            }
            return result;
        }
        catch (Exception ex)
        {
            string result = "Error occur during checking your EmaiID";
            return result;
        }
    }

Thursday, 20 June 2013

Ajax AsyncFileUpload control using javascript in asp.net

In .aspx Page:


<script type="text/javascript">
        function UploadCompleted(sender, args) {
            var filename = document.getElementById('ctl00_ContentPlaceHolder1_Label1').innerHTML;
            var imgDisplay = $get("imgDisplay");
            $get("<%=divImagetag.ClientID %>").style.display = 'block';
            imgDisplay.src = "UploadedImages/" + filename;
            $get("<%=Label1.ClientID %>").innerHTML = "Successfully uploaded!!!";
            clearContents();
        }
        function UploadError(sender, args) {
            $get("<%=Label1.ClientID %>").innerHTML = "File upload failed.";
            clearContents();
            $get("<%=divImagetag.ClientID %>").style.display = 'none';
        }
        function clearContents() {
            var span = $get("<%=AsyncFileUpload1.ClientID%>");
            var txts = span.getElementsByTagName("input");
            for (var i = 0; i < txts.length; i++) {
                if (txts[i].type == "text") {
                    txts[i].value = "";
                }
            }
        }
     
    </script>


 <table border="0" cellpadding="5" cellspacing="5">
            <tr>
                <td colspan="2">
                    <asp:Label ID="lblMessage" runat="server" Font-Bold="true" ForeColor="Red"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    <strong>Image Upload </strong>
                </td>
                <td>
                    <ajaxToolkit:AsyncFileUpload ID="AsyncFileUpload1" runat="server" Width="400px" UploaderStyle="Modern"
                        CompleteBackColor="White" UploadingBackColor="#CCDDEE" ThrobberID="inProgress"
                        OnClientUploadError="UploadError" OnClientUploadComplete="UploadCompleted" OnUploadedFileError="AsyncFileUpload1_UploadedFileError"
                        OnUploadedComplete="AsyncFileUpload1_UploadedComplete" />
                    <asp:Image ID="inProgress" runat="server" ImageUrl="~/inProgress.gif" />
                    <br />
                    <asp:Label ID="Label1" runat="server"></asp:Label>
                </td>
            </tr>
        </table>
        <div id="divImagetag" runat="server" align="center" style="display: none">
            <img id="imgDisplay" alt="" src="" height="100px" width="150px" />
        </div>

In aspx.cs page:


  protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {
        Random random = new Random();
        int randomNumber = random.Next(0, 100);
        if (AsyncFileUpload1.HasFile)
        {
            string fileextension = Path.GetExtension(e.FileName);
            if (fileextension == ".jpeg" || fileextension == ".gif" || fileextension == ".png" || fileextension == ".jpg" || fileextension == ".bmp")
            {
                string filename = randomNumber + fileextension;
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "sample", "top.$get(\"" + Label1.ClientID + "\").innerHTML = '" + filename + "';", true);
                string path = Server.MapPath(("~/UploadedImages/") + filename);
                AsyncFileUpload1.SaveAs(path);
            }
            else
            {
                lblMessage.Text = "We support only images of type jpg, gif,jpeg,bmp and png";
            }
        }
        else
        {
            lblMessage.Text = "Please Upload Image";
        }
    }
 protected void AsyncFileUpload1_UploadedFileError(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {
        lblMessage.Text = "Could not upload file!";
    }

Tuesday, 18 June 2013

Validate URL Address in ASP.NET

In aspx page:

<table>
        <tr>
            <td colspan="2" align="center">
                <asp:Label ID="lblURL" runat="server" Font-Bold="true" ForeColor="Red"></asp:Label>
            </td>
        </tr>
        <tr>
            <td>
                <strong>Enter URL:</strong>
            </td>
            <td>
                <asp:TextBox ID="txtUrlAddress" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RFV_txtUrlAddress" runat="server" ControlToValidate="txtUrlAddress"
                    Display="None" SetFocusOnError="true" ErrorMessage="Please Enter URL" ValidationGroup="Submitgp"></asp:RequiredFieldValidator>
                <ajaxToolkit:ValidatorCalloutExtender ID="VCE1_txtUrlAddress" runat="server" TargetControlID="RFV_txtUrlAddress">
                </ajaxToolkit:ValidatorCalloutExtender>
                <asp:RegularExpressionValidator ID="REV_txtUrlAddress" runat="server" ControlToValidate="txtUrlAddress"
                    ValidationExpression="http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?" ValidationGroup="Submitgp"
                    Display="None" ErrorMessage="Please Enter Valid URL" SetFocusOnError="true"></asp:RegularExpressionValidator>
                <ajaxToolkit:ValidatorCalloutExtender ID="VCE2_txtUrlAddress" runat="server" TargetControlID="REV_txtUrlAddress">
                </ajaxToolkit:ValidatorCalloutExtender>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="Submitgp"
                    OnClick="btnSubmit_Click" />
            </td>
        </tr>
    </table>

In aspx.cs code:

 protected void btnSubmit_Click(object sender, EventArgs e)
    {
        lblURL.Text = "Your URL is:" + txtUrlAddress.Text;
    }

JOINS IN SQL SERVER

create tables and insert data into tables

CREATE TABLE dbo.Table1
(ID INT, Value VARCHAR(10))
INSERT INTO dbo.Table1 (ID, Value)
SELECT 1,'First'
UNION ALL
SELECT 2,'Second'
UNION ALL
SELECT 3,'Third'
UNION ALL
SELECT 4,'Fourth'
UNION ALL
SELECT 5,'Fifth'


CREATE TABLE dbo.Table2
(ID INT, Value VARCHAR(10))
INSERT INTO dbo.Table2 (ID, Value)
SELECT 1,'First'
UNION ALL
SELECT 2,'Second'
UNION ALL
SELECT 3,'Third'
UNION ALL
SELECT 6,'Sixth'
UNION ALL
SELECT 7,'Seventh'
UNION ALL
SELECT 8,'Eighth'



Basic of joins:

INNER JOIN

This join returns rows when there is at least one match in both the tables.


Select * from Table1 t1 INNER JOIN Table2 t2 ON t1.col1=t2.col1

Ex: select t1.*,t2.* from dbo.Table1 t1 inner join dbo.Table2 t2 on t1.ID=t2.ID


OUTER JOIN:

There are three different Outer Join methods.

LEFT OUTER JOIN

This join returns all the rows from the left table in conjunction with the matching rows from the right table. If there are no columns matching in the right table, it returns NULL values.

select * from Tabel1 t1 LEFT OUTER JOIN Table2 t2 ON t1.col1=t2.col1

Ex: select t1.*,t2.* from dbo.Table1 t1 left join dbo.Table2 t2 on t1.ID=t2.ID



RIGHT OUTER JOIN
This join returns all the rows from the right table in conjunction with the matching rows from the left table. If there are no columns matching in the left table, it returns NULL values.

Select * from Table1 t1 RIGHT OUTER JOIN Table2 t2 ON t1.col1=t2.col1

Ex: select t1.*,t2.* from dbo.Table1 t1 right join dbo.Table2 t2 on t1.ID=t2.ID

FULL OUTER JOIN

This join combines left outer join and right outer join. It returns row from either table when the conditions are met and returns null value when there is no match.

select * from Table1 t1 FULL OUTER JOIN Table2 t2 ON t1.col1=t2.col1

Ex: select t1.*,t2.* from dbo.Table1 t1 Full outer join dbo.Table2 t2 on t1.ID=t2.ID

CROSS JOIN:

This join is a Cartesian join that does not necessitate any condition to join. The resultset contains records that are multiplication of record number from both the tables.

select * from Table1 t1 cross JOIN Table2 t2

Ex: select t1.*,t2.* from dbo.Table1 t1 cross join dbo.Table2 t2

Additional Notes related to JOIN:

/* LEFT JOIN - WHERE NULL */
This query using Outer Join and WHERE clause in join.
select * from Table1 t1 LEFT OUTER JOIN Table2 t2 ON t1.col1=t2.col1 WHERE t2.Col1 IS NULL

 Ex: select * from dbo.Table1 t1 left join dbo.Table2 t2 on t1.ID=t2.ID where t2.ID is null

/* RIGHT JOIN - WHERE NULL */
This query also using Outer Join and WHERE clause in join.

select * from Table1 t1 RIGHT OUTER JOIN Table2 t2 ON t1.col1=t2.col2 WHERE t1.col1 IS NULL

Ex:select t1.*,t2.* from dbo.Table1 t1 right join dbo.Table2 t2 on t1.ID=t2.ID where t1.ID is null


/* OUTER JOIN - WHERE NULL */

This join will give all the results that were not present in Inner Join.

select * from Table1 t1 FULL OUTER JOIN Table2 t2 ON t1.col1=t2.col1 WHERE t1.col1 IS NULL OR t2.col1 IS NULL

Ex:select t1.*,t2.* from dbo.Table1 t1 full outer join dbo.Table2 t2 on t1.ID=t2.ID where t1.ID is null or t2.ID is null

select statement for retriving only column names in a table

Ex1:

SELECT  *  FROM yourTableName WHERE 1=0

Ex2:


select
a.[name]
from
sys.columns a join sys.tables b on
a.object_id = b.object_id
where
b.[name] = 'YourTableName'

Friday, 14 June 2013

Remove Delete Duplicate Records Or Rows-Sql Server




First Method:

Query to delete duplicate rows.

DELETE FROM dbo.Employees
WHERE ID NOT IN (SELECT MIN(ID)
FROM dbo.Employees GROUP BY FirstName,Department)


Second method:

Query to delete duplicate rows.


WITH DuplicateRecords AS
(
SELECT *,row_number() OVER(PARTITION BY FirstName,Department ORDER BY

FirstName)
AS RowNumber FROM dbo.Employees
)
DELETE FROM DuplicateRecords WHERE RowNumber>1

This should remove all duplicate records from table.


Third Method:

Query to delete duplicate rows.


SELECT DISTINCT * INTO TempTable FROM dbo.Employees
GROUP BY FirstName,Department
HAVING COUNT(FirstName) > 1

DELETE dbo.Employees WHERE FirstName
IN (SELECT FirstName FROM TempTable)

INSERT dbo.Employees SELECT * FROM TempTable
DROP TABLE TempTable


This should remove all duplicate records from table.






Reset Identity Column Value In Sql Server Table

How To Reset Identity Column In Sql Server Table To Start Auto Increment Or Seed From Desired Number

If we delete All data from Sql Server table having Identity Column with Identity Seed as 1 and insert new data Identity column value doesn't get reset and it starts from last number.

If table were having 10 records and we insert new records after deleting all records in table, identity column would start from 11 if identity seed is 1.

we can use below mentioned command to reset Identity Column.


DBCC CHECKIDENT('YouTableName', RESEED, 0)

Check UserName Availble or Not in asp.net

In Default.aspx:

  <style type="text/css">
        .waitingdiv
        {
            background-color: #F5F8FA;
            border: 1px solid #5A768E;
            color: #333333;
            font-size: 93%;
            margin-bottom: 1em;
            margin-top: 0.2em;
            padding: 8px 12px;
            width: 8.4em;
        }
    </style>
     <script type="text/javascript">
         Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
         function BeginRequestHandler(sender, args) {
             var state = document.getElementById('loadingdiv').style.display;
             if (state == 'block') {
                 document.getElementById('loadingdiv').style.display = 'none';
             } else {
                 document.getElementById('loadingdiv').style.display = 'block';
             }
             args.get_postBackElement().disabled = true;
         }
</script>
    <div>
        <asp:UpdatePanel ID="UpdatePanel" runat="server">
            <ContentTemplate>
                <table>
                    <tr>
                        <td>
                            <strong>UserName: </strong>
                        </td>
                        <td>
                            <asp:TextBox ID="txtUserName" runat="server" AutoPostBack="true" CssClass="serachtext"
                                ontextchanged="txtUserName_TextChanged"></asp:TextBox>
                        </td>
                        <td>
                            <div id="CheckUserName" runat="server" visible="false">
                                <asp:Image ID="imgstatus" runat="server" Height="17px" Width="17px" />
                                <asp:Label ID="lblstatus" runat="server"></asp:Label>
                            </div>
                        </td>
                    </tr>
                </table>
                <div class="waitingdiv" id="loadingdiv" style="display: none; margin-left: 5.3em">
                <img src="LoadingImage.gif" alt="Loading" />Please Wait.......
                </div>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>

In Default.aspx.cs:

  protected void txtUserName_TextChanged(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(txtUserName.Text))
        {
            ds = objbal.checkUserName(txtUserName.Text);
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                CheckUserName.Visible = true;
                imgstatus.ImageUrl = "NotAvailable.jpg";
                lblstatus.Text = "UserName Alredy Exists,choose Another One";
                System.Threading.Thread.Sleep(2000);
            }
            else
            {
                CheckUserName.Visible = true;
                imgstatus.ImageUrl = "Icon_Available.gif";
                lblstatus.Text = "UserName Available";
                System.Threading.Thread.Sleep(2000);
            }

        }
        else
        {

            CheckUserName.Visible = false;
        }
    }

Stored Procedure:
create procedure dbo.checkuserId
(
@UserId varchar(50)
)
as
begin
select * from dbo.Cartoon_Admin_Login where UserId=@UserId
end


Thursday, 13 June 2013

Clear controls in asp.net using javascript

   <script type="text/javascript" language="javascript">
        function clearAllServerFields() {

            //Code for accessing all dropdown lists and listboxes in an aspx page

            var select = document.getElementsByTagName("select");
            var length = select.length;
            for (i = 0; i < length; i++) {
                for (var j = 0; j < select[i].length; j++) {
                    select[i][j].selected = false;
                }
            }

            var elements = document.getElementsByTagName("input");
            for (var i = 0; i < elements.length; i++) {
                if (elements[i].disabled == false) {
                    //Code for accessing all textboxes in an aspx page

                    if (elements[i].type == "text") {
                        elements[i].value = "";
                    }
                    //Code for accessing all radio buttons in an aspx page

                    if (elements[i].type == "radio") {
                        elements[i].checked = false;
                    }
                    //Code for accessing all checkboxes in an aspx page

                    if (elements[i].type == "checkbox") {
                        elements[i].checked = false;
                    }
                }
            }
        }

    </script>


queries of date functions in sqlserver



weekstartdate and weekenddate of current week:

select convert(varchar,DATEADD(dd, -(DATEPART(dw, GETDATE())-1), GETDATE()),103) as [WeekStart]

select CONVERT(varchar, DATEADD(dd, 7-(DATEPART(dw, GETDATE())), GETDATE()),103) as [WeekEnd]

--India Time=UTC+5:30

select convert(varchar,DATEADD(dd, -(DATEPART(dw, DATEADD(mi,30,DATEADD(hh,5,getutcdate())))-1), DATEADD(mi,30,DATEADD(hh,5,getutcdate()))),103) as [WeekStart]

select CONVERT(varchar, DATEADD(dd, 7-(DATEPART(dw, DATEADD(mi,30,DATEADD(hh,5,getutcdate())))), DATEADD(mi,30,DATEADD(hh,5,getutcdate()))),103) as [WeekEnd]


monthstartdate and monthenddate of currentmonth :

select convert(varchar,dateadd(d,-(day(getdate()-1)),getdate()),103) as [monthfirstDate]

select  convert(varchar,dateadd(d,-day(getdate()),dateadd(m,1,getdate())),103)as [monthlastDate]

--India Time=UTC+5:30

select convert(varchar,dateadd(d,-(day(DATEADD(mi,30,DATEADD(hh,5,getutcdate()))-1)),DATEADD(mi,30,DATEADD(hh,5,getutcdate()))),103) as [monthfirstDate]

select  convert(varchar,dateadd(d,-day(DATEADD(mi,30,DATEADD(hh,5,getutcdate()))),dateadd(m,1,DATEADD(mi,30,DATEADD(hh,5,getutcdate())))),103)as [monthlastDate]

Wednesday, 12 June 2013

C# Basics And Interview Questions

http://www.gointerviews.com/top-50-c-sharp-interview-questions-answers/


http://www.java2s.com/Tutorial/CSharp/CatalogCSharp.htm

stored procedure for counting Records


Create Procedure [dbo].[Buddy_DashBoard]
as
/*
exec Buddy_DashBoard
*/
begin


declare @Buddy_Total_Android int,@Buddy_Month_Android int,@Buddy_Week_Android int,@Buddy_Day_Android int

---To Get Android Users Data for dashBoard
select @Buddy_Total_Android=COUNT(*) from dbo.Buddy_tracker_User_Details BUD
where BUD.User_From='Android'
select @Buddy_Month_Android=COUNT(*) from dbo.Buddy_tracker_User_Details BUD
where MONTH(BUD.CreatedDate)=MONTH(dateadd(hh,5,dateadd(mi,30,getutcdate()))) and YEAR(BUD.CreatedDate)=YEAR(dateadd(hh,5,dateadd(mi,30,getutcdate()))) and BUD.User_From='Android'
select @Buddy_Week_Android=COUNT(*) from dbo.Buddy_tracker_User_Details BUD
where CONVERT(date,BUD.CreatedDate,103) between CONVERT(date,dateadd(d,-7,dateadd(hh,5,dateadd(mi,30,getutcdate()))),103) and CONVERT(date,dateadd(hh,5,dateadd(mi,30,getutcdate()))) and BUD.User_From='Android'
select @Buddy_Day_Android=COUNT(*) from dbo.Buddy_tracker_User_Details BUD
where CONVERT(date,BUD.CreatedDate,103)=CONVERT(date,dateadd(hh,5,dateadd(mi,30,getutcdate())),103) and BUD.User_From='Android'


select @Buddy_Day_Android as Buddy_Day_Android,@Buddy_Week_Android as Buddy_Week_Android,@Buddy_Month_Android as Buddy_Month_Android,@Buddy_Total_Android as Buddy_Total_Android

end

Tuesday, 4 June 2013

Add Youtube Videos in asp.net

 <asp:TextBox ID="txtvideourl" onclick="hide_video();" runat="server" Width="258px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfv_txtvideourl" runat="server" ControlToValidate="txtvideourl"
                        ErrorMessage="Please Enter Video URL" Display="None" SetFocusOnError="true" ValidationGroup="submitvideo"></asp:RequiredFieldValidator>
                    <ajaxToolkit:ValidatorCalloutExtender ID="vce_txtvideourl" runat="server" TargetControlID="rfv_txtvideourl">
                    </ajaxToolkit:ValidatorCalloutExtender>


 protected void btnVideo_Click(object sender, EventArgs e)
    {

        string videourl = string.Empty, filename = string.Empty;
        try
        {
            if (txtvideourl.Text.Contains("http://youtu.be"))
            {
                videourl = txtvideourl.Text;
                string[] arr = new string[5];
                arr = videourl.Split('/');
                filename = arr[3];
                if (ObjBll.Opertaions_on_Videos("", txtVideoName.Text, filename, "True", "Insert"))
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Warning", "alert(' Submited Successfully..')", true);
                    iframe_Video.Visible = true;
                    iframe_Video.Attributes["src"] = "http://www.youtube.com/embed/" + filename;
                    bind_data();
                    txt_Clear();
                }
            }
            else
            {
                txtvideourl.Focus();
                lbl_urlmsg.Text = "Enter Valid URL";
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message.ToString();
        }

Saturday, 1 June 2013

How to call java script function from code behind file in asp.net




Example:

 Declare a JavaScript function in the head tag of your design file as shown below:

<head runat="server">
    <title>Calling JavaScript From CodeBehind in asp.net file</title>
    <script type="text/javascript">
        function MyFunction() {
            alert('Demonstration Successfull..');
        }
    </script>
</head>

In order to call it from code behind, use the following code in your Page_Load

protected void Page_Load(object sender, EventArgs e)
{
    if (!ClientScript.IsStartupScriptRegistered("alert"))
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(),
            "alert", "MyFunction();", true);
    }
}

Thursday, 30 May 2013

Different Ways to use Insert Command in Sqlserver




--Simple Insert Command

Insert into Employee values('1','Rajesh');
Insert into Employee values('2','Harish');

--Insert command using Column name which specifies in which column we are going to insert  the data

Insert into Employee (emp_id,emp_name)values('3','lokesh');
Insert into Employee (emp_id,emp_name)values('4','siva');

--Insert command in which we select records from another table

Insert Employee1 select * from Employee;
Insert into Employee1 select * from Employee;

--Insert miltiple records in single Insert Command

Insert into Employee (emp_id,emp_name)
select  1,'Rajesh'
union all
select  2,'Harish';

Insert into Employee (emp_id,emp_name)values
('3','lokesh'),
('4','siva');

Wednesday, 29 May 2013

Difference between Delete and Truncate Command

Although the Delete and Truncate Commands logically does the same work of deleting the rows from the table but still there are many differences in their working. These differences are given below:-

1) Delete command maintained the logs files of each deleted row but Truncate command do not maintain the logs files for each deleted row but maintains the record for deallocation of the datapages in the log files.The deallocation of the datafiles means that the data rows still exists in the data pages but the extends have marked as empty for reuse.

2) Truncate command is much faster than delete command.

3) You can use Where clause in case of Delete command to delete a particular row but in case of Truncate command you have to delete the data from all the row since Where clause is not work with Truncate command.

4) Triggers is fired in case of Delete command only and they are not fired when Truncate command is used.

5) Truncate command resets the Identity property to its initial value whereas Delete command do not resets the Identity property of the column.

6) Delete is a DML command and Truncate is a DDL command

ACID Rules in Sql Server


ACID Rules

ACID Rules:- It is a concept for evaluation of databases and their architecture.

A:- (Atomicity) – Atomicity  states the principle of  All or none. This means that either all the SQL Statements within the transaction will be executed or no Sql statement will be executed.

C:- Consistency:- Consistency states that only valid data will be written into the database. That means if any Sql transaction violets the rules or constraints define on the database to make it consistent, then all the statements within the transaction will be Rollback. Or in other words the whole transaction will be rolled back.

I:- Isolation :- The Isolation state that if multiple transaction try to work on the database at the same time,then these transaction will not interfere with each other. It means the second transaction will not work unless and until the previous transaction completes its work and the work is commited.

D:- Durability:- Durability states that once the transaction is committed, then the database should not be lost in case of Software failures or hardware failures. Durability is maintained with the help of the  database backups and transaction logs

Tuesday, 28 May 2013

Date formatting





        format code                                              output
default                                            2011-10-20 06:59:22.590
convert(varchar,getDate(),100)    Oct 20 2011 6:59AM
convert(varchar,getDate(),101)         10/20/2011
convert(varchar,getDate(),102)   2011.10.20
convert(varchar,getDate(),103)  20/10/2011
convert(varchar,getDate(),104)         20.10.2011
convert(varchar,getDate(),105)          20-10-2011
convert(varchar,getDate(),106)          20 Oct 2011
convert(varchar,getDate(),107)         Oct 20, 2011
convert(varchar,getDate(),108)         06:59:00
convert(varchar,getDate(),109)   Oct 20 2011 6:59:00:553AM
convert(varchar,getDate(),110)         10-20-2011
convert(varchar,getDate(),111)         2011/10/20
convert(varchar,getDate(),112)         20111020
convert(varchar,getDate(),113)  20 Oct 2011 06:59:00:553
convert(varchar,getDate(),114)  06:59:00:553
convert(varchar,getDate(),120)         2011-10-20 06:59:00
convert(varchar,getDate(),121)         2011-10-20 06:59:00.553
convert(varchar,getDate(),126)   2011-10-20T06:59:00.553
convert(varchar,getDate(),127)          2011-10-20T06:59:00.553
convert(varchar,getDate(),130)          23 ?? ?????? 1432 6:59:00:553
convert(varchar,getDate(),131)         23/11/1432 6:59:00:553AM