Showing posts with label .Net. Show all posts
Showing posts with label .Net. Show all posts

Sunday, February 28, 2016

How To: Call Java Script Function from Silverlight

In this tutorial we will learn, how to call java script function from silver light using C#. HtmlPage.Window.Invoke function is used invoke the java script method from silver light application.

Add following C# code, where you want to call java script function.

HtmlPage.Window.Invoke("SayHello");

Add following java script code in aspx or html page in silver light web project.

function SayHello()
{
alert('Hello! function called from silverlight');
}

Java script function with parameters:

To call java script function with multiple input parameters, add following C# code in .cs file.

HtmlPage.Window.Invoke("SayHello", "Waqas", "A");

Add following java script function in aspx or html page in silver light web project.

function SayHello(fname, lname)
{
alert('Hello! ' + fname + ' ' + lname +
' -function called from silverlight');
}

This is all. You have done.
Build project and view in browser.

Saturday, February 27, 2016

How To: Integrate HTML Page in Silverlight Application

Integrating Html page in silver light application is little tricky at first. In this tutorial we will learn how to display html page in silver light application step by step.

Add following code in silver light  html page immediate before </form> tag.

<div id="BrowserDiv">
<div style="vertical-align:middle">
<img alt="Close" align="right" src="Images/Close.png" onclick="HideBrowser();" style="cursor:pointer;" />              
</div>
<div id="BrowserDiv_IFrame_Container" style="height:95%;width:100%;margin-top:37px;"></div>
</div>

Add following css code in page.

<style type="text/css">

#BrowserDiv
{
position:absolute;
background-color:#484848;
overflow:hidden;
left:0;
top:0;
height:100%;
width:100%;
display:none;
}

</style>

We need following javascript code to show and hide htm page.

<script type="text/javascript">

var slHost = null;
var BrowserDivContainer = null;
var BrowserDivIFrameContainer = null;
var jobPlanIFrameID = 'JobPlan_IFrame';

$(document).ready(function () {
slHost = $('#silverlightControlHost');
BrowserDivContainer = $('#BrowserDiv');
BrowserDivIFrameContainer = $('#BrowserDiv_IFrame_Container');
});

function ShowBrowserIFrame(url) {
BrowserDivContainer.css('display', 'block');
$('<iframe id="' + jobPlanIFrameID + '" src="' + url + '" style="height:100%;width:100%;" />')
.appendTo(BrowserDivIFrameContainer);
slHost.css('width', '0%');
}

function HideBrowser() {
BrowserDivContainer.css('display', 'none');
$('#' + jobPlanIFrameID).remove();
slHost.css('width', '100%');
}

</script>

Add reference to following jquery file.


<script type="text/javascript" src="Scripts/jquery-1.4.2.min.js"></script>

We have done with html page. Now we will move to silver light user control and open html page on button click.

Add following code in user control (main.xaml).


<Button Content="Show Html Page" HorizontalAlignment="Left" Margin="164,140,0,0" VerticalAlignment="Top" Width="117" Click="Button_Click"/>

Now add following button click handler and a helper function in main.xaml.cs to open html page.


private void Button_Click(object sender, RoutedEventArgs e)
{
ShowBrowser();
}

public void ShowBrowser()
{
try
{
string url = "http://webdesignpluscode.blogspot.com/";
HtmlPage.Window.Invoke("ShowBrowserIFrame", url);
}
catch (Exception ex)
{
throw ex;
}
}

This is all, We have done with code. Now create new folder 'Images' and place an image there 'Close.png' for close button.

Now build project and view in browser.

Sunday, April 26, 2015

How to Convert BitmapImage to Storage File in Windows Phone 8.1 Win RT

BitmapImage to Storage File conversion requires following steps.
  1. BitmapImage to byte array conversion.
  2. Creation of temporary StorageFile.
  3. Writing byte array data on empty storage file.
BitmapImage to byte array conversion

BitmapImage bitmap = ImageBoxPreview.Source as BitmapImage;

RandomAccessStreamReference rasr = RandomAccessStreamReference.CreateFromUri(bitmap.UriSource);

var streamWithContent = await rasr.OpenReadAsync();

byte[] buffer = new byte[streamWithContent.Size];

await streamWithContent.ReadAsync(buffer.AsBuffer(),(uint)streamWithContent.Size, InputStreamOptions.None);


Creation of temporary StorageFile

StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("temp.jpeg", CreationCollisionOption.ReplaceExisting);


Writing byte array data on empty storage file

using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
      using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
      {
               using (DataWriter dataWriter = new DataWriter(outputStream))
               {
                      dataWriter.WriteBytes(buffer);
                      await dataWriter.StoreAsync(); // 
                      dataWriter.DetachStream();
               }
               // write data on the empty file:
               outputStream.FlushAsync();
       }
        fileStream.FlushAsync();
}



Complete code will be:


Convert BitmapImage  to Storage File in Windows Phone 8.1 Win RT

Convert BitmapImage to Storage File in Windows Phone 8.1 Win RT.

Thursday, May 23, 2013

Set and Get Textbox Value inside ascx Control from ASP.NET Page

Setting and getting Textbox value inside user control (ascx control) from aspx page is a usual practice in both simple and complex projects.
In this tutorial, we will
  • Create New User Control.
  • Add User Control in aspx Page.
  • Set Textbox Value inside User Control
  • Get Textbox value From User Control

Create New User Control

  1. Right Click on Project, Click Add New Item.
  2. A pop up window will be opened.
  3. Select Web User Control from list, change its Name to 'myControl' and click Add
  4. Two files will be added with name 'myControl.ascx' and 'myControl.ascx.cs'
Replace the code in 'myControl.ascx' file with following code.
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="myControll.ascx.cs" Inherits="Controls_myControll" %>
<table>
    <tr>
        <td>
            Name :
        </td>
        <td>
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            Age :
        </td>
        <td>
            <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            Profession :
        </td>
        <td>
            <asp:TextBox ID="txtProfession" runat="server"></asp:TextBox>
        </td>
    </tr>
</table>

Add following code in 'myControl.ascx.cs' File.
    public string Name
    {
        get { return txtName.Text.ToString(); }
        set { txtName.Text = value; }
    }
    public string Age
    {
        get { return txtAge.Text.ToString(); }
        set { txtAge.Text = value; }
    }
    public string Profession
    {
        get { return txtProfession.Text.ToString(); }
        set { txtProfession.Text = value; }

    }

Add User Control in aspx Page

  1. Create New aspx Page with name ‘PageForWebControl’.
  2. Open Design View and drag and drop user control on it. Some code will be added in 'PageForWebControl.aspx' page automatically. 
Page will look like this.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageForWebControl.aspx.cs" Inherits="PageForWebControl" %>

<%@ Register src="Controls/myControll.ascx" tagname="myControll" tagprefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>   
        <uc1:myControll ID="myControll1" runat="server" />   
    </div>
    </form>
</body>
</html>

Set Textbox Value inside User Control

Add following code snippet in Page Load Event of 'PageForWebControl.aspx' page to set Values of Textbox  inside User Control.
// Setting Values in ASCX Control
        myControll1.Name = "Waqas Ali";
        myControll1.Age = "24";
        myControll1.Profession = "Computer Scientist";

Get Textbox value From User Control

Add following code snippet in Page Load Event of PageForWebControl.aspx page to get values of Textbox from User Control.
        string _name = string.Empty;
        int _age = 0;
        string _profession = string.Empty;
// Getting Values from ASCX Control
        _name = myControll1.Name;
        _age = Convert.ToInt32(myControll1.Age);
        _profession = myControll1.Profession;

Now you are all done. Run Project and test your values.

Wednesday, May 22, 2013

Difference Between string and String in C#.NET

There is no different between string and String (System.String). string is an alias for System.String in C#.Net.
They compile to the same code, so no difference at execution time. The complete list of aliases in C#.Net is

object:System.Object 
string:System.String
bool:System.Boolean
byte:System.Byte
sbyte:System.SByte
short:System.Int16
ushort:System.UInt16
int:System.Int32
uint:System.UInt32
long:System.Int64
ulong:System.UInt64
float:System.Single
double:System.Double
decimal:System.Decimal
char:System.Char

Friday, April 19, 2013

How to Enable and Disable ASP.NET TextBox Control on CheckBox Click in Java Script


  • Create New Project in Visual Studio 2010 (or in any version).
  • Add New Page ( named default.aspx ).
  • Add Following aspx Code in default.aspx page.

        <table style="width: 100%;">

            <tr>
                <td align="right" style="width: 50%">
                    <asp:Label ID="LabelClick" runat="server" Text="Click Me !!!"></asp:Label>
                </td>
                <td align="left" style="width: 50%;">
                    <asp:CheckBox ID="CheckBox" onclick="EnableDisableTextBox();" Checked="false" runat="server" />
                </td>
            </tr>
            <tr>
                <td align="right" style="width: 50%">
                    <asp:Label ID="LabelName" runat="server" Text="Name:"></asp:Label>
                </td>
                <td align="left" style="width: 50%">
                    <asp:TextBox ID="TextBoxName" runat="server" Width="70%"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td align="right" style="width: 50%">
                    <asp:Label ID="LabelAge" runat="server" Text="Age:"></asp:Label>
                </td>
                <td align="left" style="width: 50%">
                    <asp:TextBox ID="TextBoxAge" runat="server" Width="70%"></asp:TextBox>
                </td>
            </tr>
        </table>



  • Add Following Java Script Code inside head tag in default.aspx page.

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

            var CallerCheckBoxID = "<%= CheckBox.ClientID %>";
            var LblName = "<%= LabelName.ClientID %>";
            var TxtName = "<%= TextBoxName.ClientID %>";
            var LblAge = "<%= LabelAge.ClientID %>";
            var TxtAge = "<%= TextBoxAge.ClientID %>";
            if (document.getElementById(CallerCheckBoxID).checked == true) {

                document.getElementById(LblName).disabled = true;
                document.getElementById(TxtName).disabled = true;
                document.getElementById(LblAge).disabled = true;
                document.getElementById(TxtAge).disabled = true;

            }
            else {

                document.getElementById(LblName).disabled = false;
                document.getElementById(TxtName).disabled = false;
                document.getElementById(LblAge).disabled = false;
                document.getElementById(TxtAge).disabled = false;

            }
        }
    </script>

You have all done. View it in browser.
Follow me on Facebook to get more cool tutorials. -:)

Tuesday, December 18, 2012

Consume ASMX web Service in ASP.NET 4.0

In last tutorial, we learn How to Create ASMX web Service in ASP.NET 4.0. This tutorial guides how to consume it.
  • Add new aspx page. Right click on Website and click 'Add New Item'. A new window will appear.
asp.net asmx web service

  • Select 'Web Form' and name it according to your choice.
asp.net asmx web service

  • Create new object of web service by writing following code:
MyFirstWebService svc = new MyFirstWebService();
  • Call web service method by writing following code:
svc.CallmyName("Waqas Ali");

asp.net asmx web service

Saturday, November 24, 2012

How to Create ASMX web Service in ASP.NET 4.0

Asmx Web Services are easy and simple to Create and use. This tutorial guides you how to write a ASMX Web Service step by step. 
  • Open Visual studio and create new Website. 
  • Right Click on Website and Click on 'Add New Item'.
asp.net asmx web service
  • A New Window will Open, select 'Web Service' , name it and click 'Add'.
asp.net asmx webservice
  • When you click 'Add' Button, new files ( with .asmx and .cs extensions ) will be added to Project.
  • Visual Studio will add some code in it.
  • A default Web Method named 'Helloworld' will also be added in it.
asp.net asmx Web Service
  • You have created ASMX Web Service Successfully.
  • Replace 'Helloworld' Web Method with following code.
  • This is Custom Web Method we created for our ASMX Web Service.

In next tutorial, we will learn how to use this Web Service.

Tuesday, July 3, 2012

Create CLR Trigger


Steps for creating CLR Trigger


Follow these steps to create a CLR trigger of DML (after) type to perform an insert action:
Create a .NET class of triggering action
Make an assembly (.DLL) from that Class
Enable CLR environment in that database.
Register the assembly in SQL Server
Create CLR Trigger using that assembly

CLR Triggers

CLR Triggers


A CLR trigger could be a Date Definition or Date Manipulation Language trigger or could be an AFTER or INSTEAD OF trigger. Methods written in managed codes that are members of an assembly need to be executed provided the assembly is deployed in SQL 2005 using the CREATE assembly statement. The Microsoft.SqlServer.Server Namespace contains the required classes and enumerations for this objective.

Custom Exceptions


What are Custom Exceptions?


Custom Exceptions are user defined exceptions. There are exceptions other than the predefined ones which need to be taken care of. For example, The rules for the minimum balance in a Salary A/C would be different from that in a Savings A/C due to which these things need to be taken care of during the implementation.


Implement Delegates in C#.NET


Explain how to implement Delegates in C#.NET?


Here is an implementation of a very simple delegate that accepts no parameters.


public delegate void MyDelegate();// Declaration
class MyClass
{
     public static void MyFunc()
     {
         Console.WriteLine("MyFunc Called from a Delegate");
     }
     public static void Main()
     {
            MyDelegate myDel = new MyDelegate(MyFunc);
            myDel();
      }
}


What is assembly in .NET


Define assembly.


An assembly is the primary unit of a .NET application. It includes an assembly manifest that describes the assembly.


Monday, July 2, 2012

How Obfuscator works


Explain how Obfuscator works?


Obfuscators protect the source code from being hacked. Encryption and Decryption are processes from where you can get the data back. However these differ from what obfuscation is. In obfuscation, a program become out of the reach of hackers although it functions the same way it is supposed to. Optimizations too get applied to the process of obfuscation in order to make the program fast.



Obfuscator simply renames all types and namespace etc to meaningless code making it non human readable. This diminishes the possibility of reverse engineering. For example


private void AddEmp(Employee employee) 
{
   {
      this.EmpList.Add(employee);
   }
}


It gets converted to following code.


private void a(a b) 
{
    {
      a.a.Add(b);
    }
}


Abstract classes in C#.NET


Define abstract class in C#.NET.


Abstract classes in C#.NET has following features :
Abstract class cannot be instantiated.
Same concept in C++ known as pure virtual method. 
A class that must be inherited and have the methods over-ridden. 
A class without any implementation.

Constructor and Destructor in .NET


What is a Constructor? 


It is the first method that are called on instantiation of a type. It provides way to set default values for data before the object is available for use. Performs other necessary functions before the object is available for use.


What is a Destructor?


It is called just before an object is destroyed. It can be used to run clean-up code. You can't control when a destructor is called since object clean up by common language runtime.

Implement a Web Service in .NET

Explain with code sample how to Implement a Web Service in .NET?

Following is code in VBScript and C# both respectively.

In VBScript :


<%@ WebService Language="VBScript" Class="KmToMConvert" %>

Imports System
Imports System.Web.Services

Public Class KmToMConvert :Inherits WebService
   <WebMethod()> Public Function KilometerToMeter(ByVal Kilometer As String) As String 
         return (Kilometer * 1000)
         end function
end class

In C# :

[WebService(Namespace = http://tempuri.org/)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
     [WebMethod]
     public string HelloWorld()
     {
            return "Hello World";
     }
}

Private virtual methods in C#.NET


Can private virtual methods be overridden in C#.NET? 


No, moreover, you cannot access private methods in inherited classes, They have to be protected in the base class to allow any sort of access. 

Multiple inheritance in C#.Net


Does C#.Net support multiple inheritance?


No, C#.Net does not support multiple inheritance,  but we can use interfaces to achieve functionality of multiple inheritance.

What is serialization


Explain serialization ?


Serialization is a process of converting an object into a stream of bytes. .Net has 2 serializers namely XMLSerializer and SOAP/BINARY Serializer. Serialization is maily used in the concept of .Net Remoting.