Showing posts with label c#. Show all posts
Showing posts with label c#. 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.

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

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

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();
      }
}


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.

How to force garbage collector to run


Is this possible to force garbage collector to run? 


Yes, we can force garbage collector to run using following code.
System.GC.Collect().

Compilation and Execution of .Net application


Describe how a .Net application is compiled and executed?


From the source code, the compiler generates Microsoft Intermediate Language (MSIL) which is further used for the creation of an EXE or DLL. The CLR processes these at runtime. Thus, compiling is the process of generating this MSIL. The way you do it in .Net is as follows:
Right-click and select Build / Ctrl-Shift-B / Build menu, Build command
F5 - compile and run the application. 
Ctrl+F5 - compile and run the application without debugging.


Compilation can be done with Debug or Release configuration. The difference between these two is that in the debug configuration, only an assembly is generated without optimization. However, in release complete optimization is performed without debug symbols.

Event and Delegate


What is an Event?


When an action is performed, this action is noticed by the computer application based on which the output is displayed. These actions are called events. Examples of events are pressing of the keys on the keyboard, clicking of the mouse. Likewise, there are a number of events which capture your actions.


Delegate :


Delegates are kind of similar to the function pointers. But they are secure and type-safe. A delegate instance encapsulates a static or an instance method. Declaring a delegate defines a reference type which can be used to encapsulate a method having a specific signature.


Handle Exceptions in .NET 2.0


Explain how to Handle Exceptions in .NET 2.0.


There are different methods for handling the exceptions. For example


Method 1 :


try
{
     // code here
}
catch(Exceptiontype *etype_object)
{
     // code here.
}


Method 2 :
try
{
       // code
}
catch(Exceptiontype *etype_object)
{
        throw new Custom_Exception();
}

Difference between object pooling and connection pooling


How does object pooling and connection pooling differ?


In Object pooling, you can control the number of connections. In connection pooling, you can control the maximum number reached.


When using connection pooling, if there is nothing in the pool, a connection is created since the creation is on the same thread.


In object pooling, the pool decides the creation of an object depending on whether the maximum is reached which in case if it is, the next available object is returned. However, this could increase the time complexity if the object is heavy.

Sunday, July 1, 2012

Object Pooling in .NET


What is an object pool in .NET?


An object pool is a container of objects that holds a list of other objects that are ready to be used. It keeps track of following:
Objects that are currently in use
The number of objects the pool holds
Whether this number should be increased
The request for the creation of an object is served by allocating an object from the pool.


This reduces the overhead of creating and re-creating objects each time an object creation is required.