Wednesday, 30 April 2014

Srollable Tex box in windows phone 8

Design
----------
<phone:PhoneApplicationPage
    x:Class="RIMS_ParentPortal.test2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">

    <Grid x:Name="LayoutRoot" Grid.Row="1" Margin="12,0,12,0">
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="300" />
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="auto" />
        </Grid.RowDefinitions>
        <TextBlock Text="Scrolling TextBox sample" FontSize="40" />
     
        <ScrollViewer Grid.Row="1"
                   
                      Name="scroller">

            <TextBox Name="txtMessage"
                        TextWrapping="Wrap"
                        AcceptsReturn="True"
                        TextChanged="txtMessage_TextChanged"
                        GotFocus="txtMessage_GotFocus"
                        LostFocus="txtMessage_LostFocus"
                        Tap="txtMessage_Tap" />
         
        </ScrollViewer>
     
        <StackPanel Grid.Row="2">
            <Button Content="Button"/>

        </StackPanel>

        <Grid Grid.Row="3"  Name="pnlKeyboardPlaceholder" Visibility="Collapsed" />


    </Grid>

</phone:PhoneApplicationPage>

Code
------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;






using System.Windows.Media;
using System.Windows.Data;

namespace RIMS_ParentPortal
{
    public partial class test2 : PhoneApplicationPage
    {
        public test2()
        {
            InitializeComponent();
            Loaded+=test2_Loaded;
        }

        void test2_Loaded(object sender, RoutedEventArgs e)
        {
             //determine if HD device
            var deviceWidth = this.ActualWidth;
            var isHdDevice = (deviceWidth > 500 ? true : false);

            //the keyboard height differs between HD devices and regular ones
            if (isHdDevice)
                keyboardHeight = 540;
            else
                keyboardHeight = 336;

            //make the keyboard placeholder's height as high as
            //the anticipted keyboard height
            //this will be used to offset other controls on the page into the viewable area
            pnlKeyboardPlaceholder.Height = keyboardHeight;
        }

        double InputHeight;
        int keyboardHeight;
        double tapOffset;

        private void txtMessage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //capture the y position of where the user tapped
            //relative to the textbox
            tapOffset = e.GetPosition(txtMessage).Y - 80;
        }

        private void txtMessage_GotFocus(object sender, RoutedEventArgs e)
        {
            //reset any page movement cause by keyboard opening
            App.RootFrame.RenderTransform = new CompositeTransform();

            //make the keyboard placeholder visible
            //squishing the scrollviewer into the now smaller available screen area
            pnlKeyboardPlaceholder.Visibility = Visibility.Visible;

            //re-measure content panel, scrollviewer and it's contents
            //this is so that the scrollviewers available scrollable area is updated
            LayoutRoot.UpdateLayout();

            //scroll to the position of the click
            //(tapOffset set in Tap event - Tap event fires before this and provides tap offset)
            scroller.ScrollToVerticalOffset(tapOffset);

        }

        private void txtMessage_TextChanged(object sender, TextChangedEventArgs e)
        {
            Dispatcher.BeginInvoke(()=>
            {
                double CurrentInputHeight = txtMessage.ActualHeight;

                //after the user starts typing text, text will eventually wrap to the next line
                //this ensures the textbox height doesnt sink below the bottom of the scrollviewer
                if (CurrentInputHeight >= InputHeight)
                {
                    scroller.ScrollToVerticalOffset(scroller.VerticalOffset + CurrentInputHeight - InputHeight);
                }

                InputHeight = CurrentInputHeight;
            });
        }

        private void txtMessage_LostFocus(object sender, RoutedEventArgs e)
        {
            //hide the keyboard placeholder from screen
            //allowing the scrollviewer to re-occupy the available area again
            this.pnlKeyboardPlaceholder.Visibility = Visibility.Collapsed;

        }
    }
}


http://klingdigital.net/2013/06/scrollviewer-and-multiline-textbox-windowsphone/

Tuesday, 29 April 2014

ListBox in WPF

http://www.wpf-tutorial.com/list-controls/listbox-control/

Saturday, 26 April 2014

2 yr Interview Question in DotNet

Hai Friends,
In the continuation of the series of the Interview Questions in the Microsoft Technologies, I am posting few more questions which will be helpful for the Quick reference in learning the concepts related to WCF, Assembly,  Sql Server,Interface & Abstract Class etc.

1. What is the difference between Web Services and WCF.
Ans. 
A. WCF Services = Web Services + Remoting + Security + Reliability + Messaging Queue
B. Not only that, hosting is also one of the powerful feature in WCF where the service can be hosted in Self Hosting, Hosting in Windows Services, Hosting on another Service etc.
C. Supports DataContractSerializer which is fast and can serialize fields and properties.
D. Integrated Logging mechanism.

2. What are the different ways of hosting a WCF service.
Ans.

A. Hosting on Console application
B. Hosting on Windows application
C. Hosting on Windows services
D. Hosting on IIS
E. Hosting on WAS(Windows Activation Service) 

3. Explain the different types of triggers in SQL Server.
Ans.

A. DDL Trigger- Trigger fires on DDL Commands
B. DML Trigger- Trigger fires on DML Commands
C. InsteadOf Trigger- Trigger fires on View updation

4. Difference between BasicHttpBinding and WSHttpBinding.
Ans.

A. BasicHttpBinding does not enable message level security while the WSHttpBinding enables Message level as well as Transport level security.
B. BasicHttpBinding has the default windows authentication while the WSHttpBinding support WS* authentication and security.
C. BasicHttpBinding only supports HTTP to access the service while WSHttpBinding suppors HTTP and HTTPS(secure)
D. Data which travels through the BasicHttpBinding is in XML format and no encryption allowed while the data travels through WSHttpBinding goes in Encrypted format.

5. What are the different types of assemblies available in .NET?
Ans.

A. Private Assembly
B. Shared Assembly
C. Satellite Assembly

6. What is a strong name and how do you give a strong name to an assembly?
Ans.

Unique identification of an assembly called as strong name. By strong name we can differentiate the assemblies which are having the same name.
We can generate the Strong name using the command:
SN -K dllName

7. What is InsteadOf trigger.
Ans. 

To update the Views, InsteadOf trigger is used. This is the only use of InsteadOf trigger. There is no use except this.

8. Can we use Insert/Update statements in views in SQL SERVER?Ans. 
No, View works only on the Query/select command. So we can't have DML commands inside the View. So no Insert/update operations are allowed.

9. What are abstract classes and Interface and what the difference between the two.
Ans.

When the class does not provides the full functionality, the class must be declared as the abstract class.
There are 2 types of abstract classes-
A. Partial Abstract Class (Abstract Class)- Class which can support the abstract members(methods, properties) as well as concrete members(methods, properties), the class can be declared as the abstract class.
Abstract class works based on the child class memory. We can't create the object of the abstract class, only the reference can be created for the abstract class.
All the abstract members must be overrides in the child class using the Override keywords.

B. Fully Abstract class (Interface) - The collection of abstract members (methods, properties) is called as interface.
Interface contains all the abstract members.

When you have limited scope for the functionality, Abstract class is better but when there is the requirement to implement the global functions, interface is best way to do.
e.g. When u have some feature which can be implemented in several classes and classes are interrelated, use Abstract class but when the feature can be application level and used by various independent classes, use Interface.

10. What are the advantages of Interface over abstract classes? 
Ans.

When you have some feature which can be implemented in several classes and classes are interrelated, use Abstract class but when the feature can be application level and used by various independent classes, use Interface.
Interfaces are more rigid than Abstract classes.
e.g. let's say, i have a method called Show() to show the message in various classes, we can have interface for this. Now let's say, I have implemented this interface in 100 classes where I want to use the Show() method to show some message.
Tomorrow there is some requirement to have the new Print Functionality to let's say in 50 various classes. Now the one way is to add this Print() in the same interface so that we can just implement it to those classes. But what about the rest 50, where we don't want this print.. So this is drawback of Interface.
That is the reason the Single Responsibility principle and then the interface Segregation Principle came where a class/interface should have only one responsibility. Like in the above example, there are more responsibility and got the problem.
Abstract class is best when the scope is limited. Let's say I want to calculate the Area of few shapes. So we can say that this is limited as few classes can use this so we can create the abstract class with the abstract method called Area and then implement to those classes by inheriting the abstract class.
The scope of the Abstract class is till the immediate child class. So you can't use it in grand child or grandparent classes.

11. What is a sealed class?
Ans.

When the class provides full functionality, we can make the class as sealed class. Sealed class can't be inherited but it can be instantiated. it means, when the class is self-dependent, the class be made as sealed class. E.g. all data types are sealed by nature.

12. What kind of authentication mechanism you have used in your WCF project.
Ans.

There are various authentication modes which can be used for the WCF service like-
A. No Authentication- When the service doesn't requires any authentication and its public to access and use, this type of authentication mode is used.
B. Windows Authentication – This type of service depends on the windows credential so if the user is having the windows credentials, they can use and access the service.
C. Form Authentication – This type of authentication requires certain and valid user name and password to access the service.
D. Certificate Based – There are the secure cervices where each request needs certain authentication mechanism which can be the 3rdparty like X509 certificates to validate the access requests.
E. Custom Authentication- This can be mixed with two or more authentication mechanism.
F. Token Based Authentication – Depends on the token provided by the service provider. So based on the token, the client can access the service.

13. How do you configure a WCF Service to use Network Authentication?Ans. 
We need to set the remote settings for this.
Below is the reference url:
http://technet.microsoft.com/en-us/library/cc742824.aspx

14. What is Garbage Collection? How is Garbage Collector invoked in .NET?
Ans.

When the heap memory is filled with the objects and there is no memory left to accommodate the new object, Garbage collector gets called by the CLR. So it's an activity which is initiated by the run time (CLR). When the garbage collector gets called, it tries to find out each referenced objects which are in use by the applications. The objects which are not reachable, it marks them to delete. Based on the reachable objects, the garbage collector prepares the object graph, which has the reference of each reachable object. Now based on the object graph which contain the object generations too, the Garbage collector checks for the generation 0 objects and marks them for deletion and move rest of the objects to generation 1. The heap memory gets compacted for the new object and new object gets placed in the heap memory.
This is the uncertain and un-deterministic process as the Garbage collector doesn't know when it will be called. Its all based on the capacity memory of the heap. When the heap memory get filled and a new object is initiated, the runtime (CLR) calls the Garbage collector.


15. Can you force Garbage Collector to be invoked from c# code?
Ans.

Yes, When we have something called the unmanaged objects(C++, VC++,VB 6.0), then we need to explicitly release the memory. To do this, we can use the Dispose() method to free-up these object.
Sometimes, we need to force the garbage collector to be called to free-up the memory, so we can use the GC.Collect() method to do so.

16. How is var keyword used in .NET.Difference between var and dynamic keywords.
Ans. 

var keyword is newly introduces with the .net 3.5 and it is used to make the assignment for any type of data. It can store any type of data irrespective of its datatype.
So when we don't know that what type of data, the certain process will return, we can use the var keyword.
e.g.
var connection = new SqlConnection(connectionString);

Here the connection variable can store the SQLConnection type.
Dynamic keyword is newly introduces with the .net 4.0 version and is used to keep not only the any type of data but also the reference will be constant.
For the var, the type is made at the compile time while in case of Dynamic; the type is inferred in runtime.
e.g.
var customer = new Customer();
customer.GetCustomers();

Here the compiler will check for the GetCustomers()method. If the GetCustomers() method doesn't exists, it will show error during the compilation.
But for the dynamic,
dynamic  customer = new Customer();
customer.GetCustomers();

Here the compiler will not check for the GetCustomers() method during the compilation. But at the runtime, if the method is not available, it will throw error.
So the main use of dynamic is when we don't want the compiler should check for certain errors during compilation. It will skip the error if they are of dynamic type. 

17. Difference between Stored Procedures and Functions.
Ans.

Stored Procedure and Functions are the database objects which are the precompiled names sql statements.
A. Stored procedure can take in as well as Out parameters while function can take only in parameters'.
B. Stored Procedure may or may not return the value while the Function must return a value. Returning a value in stored procedure depends on the input parameter. If the input parameter is of type out, then it will return the value.
C. We can use the function inside the stored procedure but stored procedure can't be used inside a function.

18. What are the different types of contracts available in WCF
Ans.

A. Service Contract
B. Operation Contract
C. Data Contract
D. Message Contract
E. Fault Contract
Hope it will be helpful to you.

Thursday, 24 April 2014

Windows Application close current window open another window.Another windows close event trigger shows parent window

  First Window code for button click
          SecondWindow rfisreport = new SecondWindow();
            rfisreport.Parent = this;
            this.Hide();
            rfisreport.Show();

Second Window Code

 public FirstWindow Parent;

 protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            if(Parent!=null)              
            {
                Parent.Show();
            }
        }

DisConnected Architecture in ADO.Net

DisConnected Architecture in ADO.Net using stored procedure
-----------------------------------------------------------------------
string sqlConstring = System.Configuration.ConfigurationManager.AppSettings["SqlConnectionString"];
            SqlConnection Con = new SqlConnection();
            Con.ConnectionString = sqlConstring;
            SqlCommand cmd = new SqlCommand();
            cmd = Con.CreateCommand();
           
            cmd.CommandText = "RFID_GET_RFID_IssueDetails";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Admn_No", "");
            cmd.Parameters.AddWithValue("@Status", "Full");
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds =new DataSet();
            da.Fill(ds);
         
            return ds.Tables[0];


DisConnected Architecture in ADO.Net using string query

 string sqlCon = System.Configuration.ConfigurationManager.AppSettings["SqlConnectionString"];
            SqlConnection Con = new SqlConnection(sqlCon);
            SqlDataAdapter da = new SqlDataAdapter("Select * from RFID_ISSUE_DETAILS", Con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds.Tables[0];

Wednesday, 23 April 2014

Windows App Error log

  public static class ErrorLog
    {

       static string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log.txt"); //@"c:\RFIDLOG\log.txt";

        public static void WriteError(string error)
        {
            try
            {
                //StreamWriter sw = File.AppendText("log.txt");
                //sw.WriteLine(DateTime.Now + Environment.NewLine);
                //sw.WriteLine(error + Environment.NewLine);
                //sw.WriteLine(Environment.NewLine);
                //sw.Close();

                if (!File.Exists(path))
                {
                    // Create a file to write to.
                    using (StreamWriter sw = File.CreateText(path))
                    {
                        sw.WriteLine(DateTime.Now + Environment.NewLine);
                        sw.WriteLine(error + Environment.NewLine);
                        sw.WriteLine("---------------------------------------");

                    }
                }
                else
                {
                    using (StreamWriter sw = File.AppendText(path))
                    {
                        sw.WriteLine(DateTime.Now + Environment.NewLine);
                        sw.WriteLine(error + Environment.NewLine);
                        sw.WriteLine("---------------------------------------");

                    }
                }
            }
            catch (Exception)
            {
                //
            }
        }
    }

Thursday, 17 April 2014

Backstack or back page in windows phone

Simply use NavigationService.GoBack(); instead of using
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
It will clear all catch automatically.
or you can use NavigationService.RemoveBackEntry(); when coming again to read second article. Use something like-
int a = NavigationService.BackStack.Count();
while (a > number) //number is stack count when comes to main page first time
{
     this.NavigationService.RemoveBackEntry();
     a = NavigationService.BackStack.Count();
}



http://stackoverflow.com/questions/17065713/windows-phone-8-back-button

Project dependencies

How to: Create and Remove Project Dependencies

Visual Studio 2013
0 out of 2 rated this helpful Rate this topic
When building a solution that contains multiple projects, it can be necessary to build certain projects first, to generate code used by other projects. When a project consumes executable code generated by another project, the project that generates the code is referred to as a project dependency of the project that consumes the code. Such dependency relationships can be defined in the Project Dependencies Dialog Box.

To assign dependencies to projects

  1. In Solution Explorer, select a project.
  2. On the Project menu, choose Project Dependencies.
    The Project Dependencies dialog box opens.
    Note Note
    The Project Dependencies option is only available in a solution with more than one project.
  3. On the Dependencies tab, select a project from the Project drop-down menu.
  4. In the Depends on field, select the check box of any other project that must build before this project does.
Your solution must consist of more than one project before you can create project dependencies.

To remove dependencies from projects

  1. In Solution Explorer, select a project.
  2. On the Project menu, choose Project Dependencies.
    The Project Dependencies dialog box opens.
    Note Note
    The Project Dependencies option is only available in a solution with more than one project.
  3. On the Dependencies tab, select a project from the Project drop-down menu.
  4. In the Depends on field, clear the check boxes beside any other projects that are no longer dependencies of this project.

Spinning bar Windows phone 8

Wednesday, 16 April 2014

Advance Search dynamic where query

 private string GenerateQuery()
        {

            string sAnd = " AND ";

            StringBuilder sqlQuery = new StringBuilder();        

            if (txt_Admn_No.Text != "" )
            {
                sqlQuery.Append(" Admn_No='" + txt_Admn_No.Text + "' ");
            }
            if (cmbo_Class.SelectedIndex >0)
            {
                if (sqlQuery.Length > 0)
                {
                    sqlQuery.Append(sAnd);
                }
                sqlQuery.Append( " Course_det_id=" + cmbo_Class.SelectedValue);
            }
            if (cmbo_Batch.SelectedIndex >0)
            {
                if (sqlQuery.Length > 0)
                {
                    sqlQuery.Append(sAnd);
                }
                sqlQuery.Append( " batch_Id=" + cmbo_Batch.SelectedValue);
            }

            return sqlQuery.ToString();
        }

C# code for Advance Search

A slight bit of overkill in this simple case but I've used code similar to this in the past.
Create a function
string AddCondition(string clause, string appender, string condition)
{
    if (clause.Length <= 0)
    {
        return String.Format("WHERE {0}",condition);
    }
    return string.Format("{0} {1} {2}", clause, appender, condition);
}
Use it like this
string query = "SELECT * FROM Table1 {0}";
string whereClause = string.Empty;

if (condition 1)
    whereClause = AddCondition(whereClause, "AND", "Col=1");

if (condition 2)
    whereClause = AddCondition(whereClause, "AND", "Col2=2");

string finalQuery = String.Format(query, whereClause);
This way if no conditions are found you don't even bother loading a where statement in the query and save the sql server a micro-second of processing the junk where clause when it parses the sql statement.