Wednesday, 22 August 2018

Xamarin WCF Call


Xamarin is a popular software platform for cross platform software development.Xamarin is used for development of mobile applications for both windows ,Android and iOS platform. Xamarin comes with Microsoft Visual Studio package and code can be written in Visual Studio language likes C#. 

In this lesson we will learn how to develop a Xamarin application that connect and WCF service.For this purpose , we have build two project.One project is WCF service another project for calling the WCF service. The second project will be written on Xamarin.

WCF service Project
open Visual Studio, from the "File" menu select "New Project", then choose "WCF". A new project will be open.





An interface will automatically created, the name of interface  "IService1" interface.We have to declare service contract.Below is the code of service contract. 


[ServiceContract]
public interface IService1
{
        [OperationContract]
           string GetMessage(string Name);

       [OperationContract]
         string GetMemberName(string ClientId, string SessionId);

       [OperationContract]
          string GetConection(string clientID);

}


Now , we have to build a message contact.Below is the code of Message Contract.


[MessageContract]
          public class RemoteFileInfo : IDisposable
        {
                   [MessageHeader(MustUnderstand = true)]
                    public string FileName;

                   [MessageHeader(MustUnderstand = true)]
                   public long Length;

                   [MessageBodyMember(Order = 1)]
                   public System.IO.Stream FileByteStream;

                   public void Dispose()
                  {
                        if (FileByteStream != null)
                          {
                                FileByteStream.Close();
                                FileByteStream = null;
                         }
                }
}



Here is the full code of the file

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.IO;
[ServiceContract]
public interface IService1
{
           [OperationContract]
           string GetMessage(string Name);

           [OperationContract]
           string GetMemberName(string ClientId, string SessionId);

           [OperationContract]
           string GetConection(string clientID);

}

[MessageContract]
public class RemoteFileInfo : IDisposable
{
             [MessageHeader(MustUnderstand = true)]
             public string FileName;

              [MessageHeader(MustUnderstand = true)]
              public long Length;

              [MessageBodyMember(Order = 1)]
              public System.IO.Stream FileByteStream;

              public void Dispose()
              {
                     if (FileByteStream != null)
                     {
                           FileByteStream.Close();
                           FileByteStream = null;
                      }
             }
}

 We have modified our web.config for this purpose.here is the full code of web.config.


xml version="1.0"?>
<configuration>
<system.web>
                  <compilation debug="true" targetFramework="4.0" />
                       <httpRuntime maxRequestLength="2097151" useFullyQualifiedRedirectUrl="true" executionTimeout="14400" />
               <webServices>
                  <protocols>
                       <remove name ="Documentation"/>
                             <add name="HttpGet"/>
                             <add name="HttpPost"/>
                   </protocols>
                  </webServices>
</system.web>
<system.webServer>
                <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>

<system.serviceModel>
<services>
             <service name="wcf.Service1" behaviorConfiguration="ServiceBehavior">
            
             <endpoint address="http://localhost:8080/Service1" binding="wsHttpBinding"    contract="IService1">
<identity>
                 <dns value="localhost"/>
</identity>

</endpoint>
             <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<bindings>
              <basicHttpBinding>
               <binding name="wcf.IService1" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" transferMode="Streamed" >
                 <readerQuotas maxDepth="32" maxBytesPerRead="200000000" maxArrayLength="200000000" maxStringContentLength="200000000" />
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">

<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>

</system.serviceModel>

</configuration>

Now we have added a class file "Program.cs". The full code of program file is.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using System.ServiceModel.Description;
using wcf;

namespace ServiceHost1
{
class Program
{
static ServiceHost m_svcHost = null;
static void Main(string[] args)
{

string strAdr = "http://localhost:8080/Service1";
try
{
                Uri adrbase = new Uri(strAdr);
               m_svcHost = new ServiceHost(typeof(wcf.Service1), adrbase);

               ServiceMetadataBehavior ServiceBehavior = new ServiceMetadataBehavior();
               m_svcHost.Description.Behaviors.Add(ServiceBehavior);
                m_svcHost.AddServiceEndpoint(typeof(IMetadataExchange),
               MetadataExchangeBindings.CreateMexHttpBinding(), "mex");

                BasicHttpBinding httpb = new BasicHttpBinding();
                m_svcHost.AddServiceEndpoint(typeof(wcf.IService1), httpb, strAdr);
                m_svcHost.Open(); 
 
Console.WriteLine("Host is Starting " + DateTime.Now.ToString());
Console.ReadLine();
}
catch (Exception eX)
{
}
}
}
}
Run the application , you will get a blank screen.


Application for Consume WCF Service
Open visual studio, File >>New Project>>



Select Single View App
A new project will be open.From the Solution explorer,Layout folder,select activity_main.axml.Go to source of the file.



Add "IService1" cs file same as WFc project.
Below is the code of "IService1.cs"

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

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.ServiceModel;
using System.IO;

[ServiceContract]
public interface IService1
{
        [OperationContract]
         string GetMessage(string Name);

        [OperationContract]
        string GetMemberName(string ClientId, string SessionId);

        [OperationContract]
        string GetConection(string clientID);

         [OperationContract]
        string GetdataWCF(string names);
}

[MessageContract]
public class RemoteFileInfo : IDisposable
{
       [MessageHeader(MustUnderstand = true)]
       public string FileName;

      [MessageHeader(MustUnderstand = true)]
      public long Length;

       [MessageBodyMember(Order = 1)]
       public System.IO.Stream FileByteStream;

       public void Dispose()
      {
            if (FileByteStream != null)
             {
            FileByteStream.Close();
            FileByteStream = null;
           }
     }
}

Add code for adding button


<Button
android:id="@+id/BtnLogin"
android:layout_width="100dp"
android:layout_height="45dp"
android:text="Call WCF"
android:background="#F18D00"
android:gravity="center" />

Open file MainActivity.cs , modify the existing code to handle the click event.


protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);

SetContentView(Resource.Layout.activity_main);
Button btn = FindViewById
btn.Click += Login;
}



Here is the code for callinh WFC

ChannelFactory channelFactory = null;
EndpointAddress ep = null;
string result = string.Empty;

string strEPAdr = "http://" + "you host ip address:8080/Service1";

try
{
ep = new EndpointAddress(strEPAdr);
BasicHttpBinding httpb = new BasicHttpBinding();
channelFactory = new ChannelFactory(httpb);
IService1 mathSvcObj = channelFactory.CreateChannel(ep);

result=mathSvcObj.GetdataWCF(data);

channelFactory.Close();
}
catch (Exception eX)
{
Console.WriteLine("Error while performing operation [" + eX.Message + "] \n\n Inner Exception [" + eX.InnerException + "]");
}



Tuesday, 21 August 2018

SQL Server to text/CSV file export

There are several to export data from SQL server to text file. There are more than 8 way to export data from SQL server to a csv file.We will discuss here , three easy way to export data from SQL server to csv file.

Export query result to the external  csv file.
1)Open query analyzer, write your query.


2)From the menu, choose tool menu, select option.

3)A new window will be open. 

4)Select Query Result.

5)From the drop down select "Result to file ",then set location of your text file.



Now executive query. Now open your file, you will see that the result set is in you file.




Export table data
You can export the whole table data to csv. 


1)From the object Explorer, select database.Right click on database,a context menu will appear.Select Task>>Export Data.



 2)A new window will appear.Click on "Next".




3)Choose your authentication , then click on "Next".





4)Select Destination "Flat File Destination". Select "File Name" by Browsing your target file.then click on "Next"






5) Click on Next.




SQL Bulk copy
 

SQL server have a smart way to export data to the text file. SQL bulk copy is a good option to export data to external text file with very fast and accurate manner. Exporting data one by one row  is very time consuming a slow process. SQL bulk copy, copy data as a bulk  and write to file as a bulk. "bcp" is the comment used for bulk copy of data.


Below is the example of SQL bulk copy. We have created a table called "
tbl_bulkcopy" and insert data into it.A text file is created called "bulkcopy.txt". Now using "bcp" command to export the data to the text file.

--1. we are createing a table first
CREATE table tbl_bulkcopy
(
id    INT identity,
name  VARCHAR(50),
roll  INT
)
--insert data to the table
INSERT INTO tbl_bulkcopy(name,roll) VALUES('Ayan',20)
INSERT INTO tbl_bulkcopy(name,roll) VALUES('John',21)

--declare some use ful variable
DECLARE @fp             NVARCHAR(200)
DECLARE @fn             NVARCHAR(200)
DECLARE @sql            NVARCHAR(200)
DECLARE @opqry            NVARCHAR(200)

--set values of the variable
SELECT @fp ='C\copypath\'
SELECT @fn ='bulkcopy.txt'
SELECT @opqry='type '+@fp+@fn
---
---write the select query
SELECT @sql='SELECT name ,roll FROM tbl_bulkcopy'
---create the bulk copy script
SET @sql =  'bcp ' + '"' +  @sql + '"' +  '  queryout "' + @fp + @fn +'"   -c -q -C1252 -T '
--run the script in command shell
EXECUTE master..xp_cmdshell @sql
--
--to see the output of the file , please write the code
--or you can open the file directly
EXECUTE master..xp_cmdshell @opqry













Monday, 20 August 2018

SQL Server Rename Table, Trigger ,View

Rename View

Sometimes ,it is necessary to rename view. There is two ways to rename a View. You can do it from object Explorer ,or you can do it by writing script. Here's the step ,how can we change the name of a view from object Explorer. 

1)Form object Explorer select database 
2)Select view, right click on the view you will get a context menu. 3)Select rename, write the name of the view . 




You can also rename a View using "sp_rename". Below is example of view rename.For example , we have created a view as name "Student_List" and renamed it "new_Student_List"

 
CREATE VIEW Student_List AS
SELECT * FROM STUDENT

EXEC sp_rename 'dbo.Student_List', 'new_Student_List'

Rename Trigger

You can rename a  Trigger. Trigger can be the name from two places one from object Explorer and other from t-sql. Here's the step ,how can we change the name of a Trigger from object Explorer.


1)Form object Explorer select database 
2)Select Trigger, right click on the Triggeryou will get a context menu.  
3)Select rename, write the name of the Trigger.

You can also rename a Trigger using "sp_rename". Below is example of Trigger rename.For example , we have created a Trigger as name "tr_student" and renamed it "new_tr_student"
 
CREATE TRIGGER tr_student
ON STUDENT
         AFTER INSERT, UPDATE, DELETE
         AS PRINT ('You made one DML operation');
GO

EXEC sp_rename 'dbo.tr_student', 'new_tr_student'


Rename Table

You can rename a  Table. Table can be the name from two places one from object Explorer and other from t-sql. Here's the step ,how can we change the name of a Table from object Explorer.


1)Form object Explorer select database 
2)Select Table, right click on the Table you will get a context menu.  
3)Select rename, write the name of the Table.



You can also rename a Table using "sp_rename". Below is example of Table rename.For example , we have created a Table as name "STUDENT" and renamed it "new_STUDENT"


CREATE TABLE STUDENT
(
[student_name] VARCHAR(500),
[class] INT,
[section] VARCHAR(5),
[marks] INT
);


EXEC sp_rename 'dbo.STUDENT', 'new_STUDENT'

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...