Monday, March 31, 2014

Write/Read data into file in Android

Function to write text to file.

 private void writeToFile(String text) throws IOException {
   
  File file= new File("sdcard/android.file"); //location to write
  if (!file.exists())
  {
     try
     {
        file.createNewFile();
     }
     catch (IOException e)
     {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
  }
  try
  {
     //appending data to file
     BufferedWriter writeBuffer = new BufferedWriter(new FileWriter(file, true));
      writeBuffer .append(text);
      writeBuffer .newLine();
      writeBuffer .close();
  }
  catch (IOException e)
  {
     // TODO Auto-generated catch block
     e.printStackTrace();
  }
}

Function to read the text from file 

private String readFromFile() {
        File file= new File("sdcard/android.file"); //location to read
        StringBuilder text = new StringBuilder();
        try {
            BufferedReader readBuffer = new BufferedReader(new FileReader(file));
            String line;
            while ((line = readBuffer.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
        }
        catch (IOException e) {
            //error handling.
        }
        return text.toString();
    }

Sunday, September 29, 2013

 Basic Intro to Cursor in MS SQL


Cursor works as a foreach loop in ms sql.  
@@FETCH_STATUS = 0 -> The FETCH statement was successful if  ,
@@FETCH_STATUS = -1 -> The FETCH statement failed or the row was beyond the result set,
@@FETCH_STATUS = -2 -> The row fetched is missing.


DECLARE @ServiceId INT
    DECLARE @ContentId INT
    DECLARE @ContentExist INT = 1

    --cursor start
    DECLARE monitoring_cursor CURSOR
    FOR
    SELECT ID
        ,ContentID
    FROM dbo.[Services]
   
    OPEN monitoring_cursor

    FETCH NEXT
    FROM monitoring_cursor
    INTO @ServiceId
        ,@ContentId



    WHILE @@FETCH_STATUS = 0
    BEGIN
        IF NOT EXISTS (
                SELECT *
                FROM dbo.ContentData
                WHERE ContentID = @ContentId
                  )
        BEGIN
            SET @ContentExist = 0;
        END

        IF @ContentExist = 0
        BEGIN
            INSERT INTO dbo.Monitoring (
                [Date]
                ,[Status]
                ,[Description]
                )
            VALUES (
                GETDATE()
                ,'Failed'
                ,'Service' + @ServiceId + 'no content'
                )
        END
        ELSE
        BEGIN
            INSERT INTO dbo.Monitoring (
                [Date]
                ,[Status]
                ,[Description]
                )
            VALUES (
                GETDATE()
                ,'OK'
                ,NULL
                )
        END

        FETCH NEXT
        FROM monitoring_cursor
        INTO @ServiceId
            ,@ContentId
    END

    CLOSE monitoring_cursor

    DEALLOCATE monitoring_cursor
        --- cursor end

Wednesday, September 25, 2013

Function To Check ASCII or UTF-8 Format


public string CheckEncoding(string input)
        {
            string returnValue = String.Empty;
            string sOut = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(input));
            if (input == sOut)
            {
                return "ASCII";
            }
            else
            {
                var utf8Format = Encoding.UTF8;
                byte[] b = utf8Format.GetBytes(input);
                int taster = b.Length;
                bool checkUtf8 = false;
                if (b.Length >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF)
                {
                   checkUtf8 = true;
                }
                else
                {
                    int i = 0;
                    while (i < taster - 4)
                    {
                        if (b[i] <= 0x7F)
                        {
                            i += 1;
                            continue;
                        }
                        if (b[i] >= 0xC2 && b[i] <= 0xDF && b[i + 1] >= 0x80 && b[i + 1] < 0xC0)
                        {
                            i += 2;
                            checkUtf8 = true;
                            continue;
                        }
                        if (b[i] >= 0xE0 && b[i] <= 0xF0 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 &&
                            b[i + 2] < 0xC0)
                        {
                            i += 3;
                            checkUtf8 = true;
                            continue;
                        }
                        if (b[i] >= 0xF0 && b[i] <= 0xF4 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 &&
                            b[i + 2] < 0xC0 && b[i + 3] >= 0x80 && b[i + 3] < 0xC0)
                        {
                            i += 4;
                            checkUtf8 = true;
                            continue;
                        }
                        checkUtf8 = false;
                        break;
                    }
                }
                if(checkUtf8 == true)
                {
                    returnValue = "UTF-8";
                }
            }
            return returnValue;
        }

Saturday, September 7, 2013

Basic Introduction To ASP.NET - MVC 3 Framework


  • First of all, install mvc 3 framework. Download From: http://www.asp.net/mvc/mvc3.
  • After installing, Open Microsoft Visual Studio. Goto File and Create a New Project.
  • Choose ASP.NET MVC 3 Web Application and choose the Empty Template / Internet Application.
  • Now in Solution Explorer, right click the Controllers Folder and add Controller. (Lets name it HomeController). Also add a model in Model Folder (Lets name it HomeModel).
  • Open the HomeController.cs and modifiy it as: (include using MvcApplication1.Models)





  • Open SQL server and in your database, create a table. Here, infoTable is created as:






  • Open the HomeModel.cs and modifiy it as: (include using MvcApplication1.Connection)






  • Here, In Connection FolderDatabaseConnection class method getConnection() returns connection string where you define your connection to your server,database.






  • Then add a View by clicking inside public ActionResult Index() method.






  • Open Index.cshtml and write the html code.




  • demo.css looks like:




  • Output :


NOTE:


  • Content Folder include all css files and images that are being used by the project.
  • Global.asax.cs  includes the public static void RegisterRoutes(RouteCollection routes) method where default controller and its view can be set as per required during build.







Wednesday, August 28, 2013

Creating and Deploying a Simple WCF service (VS'10-C#)

WCF (Windows Communication Foundation) services supports more protocols for transporting messages between software entities (including protocols: HTTP,TCP,MSMQ{Microsoft Message Queuing}).But ASP.NET Web Services only supports HTTP protocol.

STEP I 

Creating a table


  • Open MS SQL Server, Goto Object Explorer tab , Select your Database and Create a table.
  • Here I'm creating a table 'productTable ' in DREAMTECH (data source) -> allTest (Database) and Fill it as shown below:
   
Fig: productTable

STEP II

Creating a WCF Service

  • Open Visual studio and Create File -> New Website-> WCF Service
  • Expand App_Code Folder in Solution Explorer.
  • Open IService.cs file and Comment all code which is inside public interface IService and rewrite (include namespace = using System.Data; ) :
            [ServiceContract]
            public interface IService{
            [OperationContract]
            DataSet queryInventoryById(int productId);
            }
  • Open Service.cs file and Comment all code inside public class Service : IService and rewrite (include namespace =  using System.Data; and  using System.Data.SqlClient; ) :
         public class Service : IService
         {       
        public DataSet queryInventoryById(int productId){
        SqlConnection sc = new SqlConnection("data source=DREAMTECH; Initial Catalog=allTest;
         User id =sa;  Password=sushil47");
        SqlDataAdapter sa = new SqlDataAdapter("Select * from productTable where                                             productId="+productId+"",sc);
        DataSet ds = new DataSet();
        sa.Fill(ds);
        return ds;
                  }
            }

  • Build it (F5) and copy "http://localhost:9715/WCFServiceTest/Service.svc?singleWsdl" .

STEP III

Creating a WCF application

  •  Open Visual studio and Create File -> New Website-> ASP.NET Website
  •  Open Default.aspx in designer mode and Drag a textbox(id=txtProductId), button(id=btnProcess) and gridview(id=GridView1).
  •  Now Goto Solution Explorer and on root website path -> Add Service Reference.

  •  Copy the previous link in the Address section and Press OK.
  • On button event write the following code (Default.aspx.cs):
       protected void btnProcess_Click(object sender, EventArgs e)

    {
        int productId = Convert.ToInt32(txtProductId.Text);
        ServiceReference1.ServiceClient objServiceProxy = new ServiceReference1.ServiceClient();
        GridView1.DataSource = objServiceProxy.queryInventoryById(productId).Tables[0];
        GridView1.DataBind();
    }
  •    Build it and Result will be:





Friday, August 16, 2013

Timespan Use

   
string sHours = '03:00:00';
int hoursInt;
TimeSpan ts = TimeSpan.Parse(sHours);
hoursInt = ts.TotalHours;

Result:

 hoursInt = 3

Note: Can compute TotalDays, TotalMinutes, TotalSeconds, TotalMilliseconds

Monday, August 12, 2013

Converting integer hours to datetime format in MS SQL SERVER 


DECLARE @DateTimeHours datetime
DECLARE @IntHours  int
SET @IntHours  =  3
SET @DateTimeHours = CONVERT(datetime,CONVERT(varchar, DATEADD(SECOND, @IntHours *3600, 0), 24))

OUTPUT:
1900-01-01 03:00:00.000

If you want to convert in present datetime:


 SET @DateTimeHours = CONVERT(varchar,GETDATE(),103) + CONVERT
(datetime,CONVERT(varchar, DATEADD(SECOND, @IntHours *3600, 0), 24))

OUTPUT:
2013-08-12 03:00:00.000