Friday, 29 April 2016

aquiry

public void asyncJson() {
        ConstantData.Displayprogress(Login.this);

        //perform a Google search in just a few lines of code
        JSONObject postJson = new JSONObject();

        JSONObject obj = new JSONObject();

        JSONArray array = new JSONArray();

        TelephonyManager telephonyManager = (TelephonyManager) Login.this                .getSystemService(Context.TELEPHONY_SERVICE);


        try {

            obj.put("userid", "" + etemail.getText());
            obj.put("password", "" + etpassword.getText());
            obj.put("deviceId", "" + telephonyManager.getDeviceId());


            Log.i("json", obj.toString());


        } catch (Exception e) {
            // TODO: handle exception        }


        final AQuery aq = new AQuery(Login.this);


        aq.post(ConstantData.LoginSevice, obj, JSONObject.class, new AjaxCallback<JSONObject>() {

            @Override            public void callback(String url, JSONObject json, AjaxStatus status) {


                if (json != null) {

                    try {
                        ConstantData.progressclose(Login.this);

                        JsonResult jsonResult = new JsonResult();
                        JsonElement json2 = new JsonParser()
                                .parse(json.toString());

                        Type type = new TypeToken<JsonResult>() {
                        }.getType();
                        jsonResult = new Gson().fromJson(json2,
                                type);

                        if (jsonResult.getResult().equalsIgnoreCase("success")) {

                            if (jsonResult.getData().isToken()) {


                                SharedPreferences editor = getSharedPreferences(
                                        ConstantData.MyPREFERENCES, 0);

                                SharedPreferences.Editor editor2 = editor
                                        .edit();

                                Intent intent = new Intent(Login.this, FragmentContainerActivity.class);

                                if (editor.getString("userid", "").equalsIgnoreCase(""))
                                    intent.putExtra("isfirsttime", true);
                                else                                    intent.putExtra("isfirsttime", false);


                                if (ck_reamind.isChecked())
                                    editor2.putBoolean("checked", true);
                                else                                    editor2.putBoolean("checked",
                                            false);

                                editor2.putString("userid", etemail                                        .getText().toString());
                                editor2.putString("password", etpassword                                        .getText().toString());
                                editor2.commit();

                                String urll = jsonResult.getData().getProfile().getUpLoadPhoto();

                                urll = urll.replace("~", "");


                                Log.v("path is", ConstantData.DISPLAY_PICTUR_URL + urll);

                                new LoadImage().execute(ConstantData.DISPLAY_PICTUR_URL + urll);


                                if (ck_reamind.isChecked())
                                    Util.setSharePrefranceData(Login.this, jsonResult.getData().getProfile().getJsonString(), ConstantData.SHARED_PREFERENCES_Profile_Object);


                                startActivity(intent);
                                finish();


//                                Toast.makeText(aq.getContext(), jsonData.getString(ConstantData.MESSAGE), Toast.LENGTH_LONG).show();                            } else {

                                ConstantData.DisplayAlert("Message", jsonResult.getData().getMessage(), Login.this);

                            }
                        }

                    } catch (Exception ex) {
                        Toast.makeText(aq.getContext(), "Error :" + json.toString(), Toast.LENGTH_LONG).show();
                    }


                } else {
                    ConstantData.progressclose(Login.this);
                    //ajax error, show error code                    Toast.makeText(aq.getContext(), "Error:" + status.getCode(), Toast.LENGTH_LONG).show();
                }
            }
        });

    }

constant data

package com.cygnus.apmlive;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.view.Window;

import com.datatype.apmtest.RecallingData;
import com.datatype.apmtest.UserData;

public class ConstantData {
// public static UserData LoginUser;

public static UserData LoginUser;
static Dialog dialog;
static Dialog dialog2;
static Dialog dialog_;

// Pref to Store user data
public static final String MyPREFERENCES = "MyPrefsSwift";

public static String customername = "";
public static String officername = "";

public static String totalcft = "";

public static String decvalue = "";

public static String imei = "";

public static final String ServerUrl = "http://223.30.71.118/Service2.svc/";

public static final String ServerUrl_survey = "http://223.30.71.117//ApplicationDoc//SurveyPDF//";

public static final String ServerUrl_quotation = "http://223.30.71.117//ApplicationDoc//QuotationPDF//";

public static final String ServerUrl_cfr = "http://223.30.71.117//ApplicationDoc//CFRPDF//";


public static final String ServerUrl_Docket = "http://223.30.71.118/Service3.svc/";


public static Docket_data passdata ;


public static String CardType = "";

public static String CustomerMobile = "";
public static String ExternalRefNum = "";

public static String InvoiceNumber = "";
public static String NameOnCard = "";

public static String PaymentMode = "";

public static String TransactionId = "";
public static double Amount = 0.00;

public static String AuthCode = "";

public static String BatchNumber = "";


public static String LastFourDigits = "";



public static String gcnumber = "";

public static String Version = "";

public static RecallingData passrecalling;
// ===============wishal===========

public static String parseenqdatass;
// ==========================
// public static CfrData cfrdatas;

public static String parseenqdatassss;

public static String directpassenquirydata;

public static JSONObject passenquirydataforsurvey;

public static String lat = "0.00";

public static String lon = "0.00";




public static boolean isValidEmail(String email) {
String EMAIL_PATTERN = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}

public static void SetUserData(Context context) {
SharedPreferences sharedpreferences = context.getSharedPreferences(
MyPREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();

editor.putString(UserData.prefpassword, LoginUser.password);
editor.putString(UserData.prefBrachName, LoginUser.getBrachName());

editor.putString(UserData.prefBranchCode, LoginUser.getBranchCode());

String RemoveSpaceUserId = LoginUser.getUserId().trim();
Log.v("removespace", "msg" + RemoveSpaceUserId);

editor.putString(UserData.prefUserId, RemoveSpaceUserId);
editor.putString(UserData.prefName, LoginUser.getName());

editor.commit();
}

public static UserData GetUserData(Context context) {

SharedPreferences prefs = context.getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
ConstantData.LoginUser = new UserData();

try {
ConstantData.LoginUser.password = prefs.getString(
UserData.prefpassword, "");
ConstantData.LoginUser.setBrachName(prefs.getString(
UserData.prefBrachName, ""));

ConstantData.LoginUser.setBranchCode(prefs.getString(
UserData.prefBranchCode, ""));
ConstantData.LoginUser.setName(prefs.getString(UserData.prefName,
""));
ConstantData.LoginUser.setUserId(prefs.getString(
UserData.prefUserId, ""));

} catch (Exception e) {
ConstantData.LoginUser.setUserId("");
ConstantData.LoginUser.password = "";
}

return ConstantData.LoginUser;
}

public static SimpleDateFormat dateformate = new SimpleDateFormat(
"dd MMM yyyy");

public static SimpleDateFormat dateformatesurvey = new SimpleDateFormat(
"dd MMM yyyy HH:mm");

public static Object cfrparsdata;

public static JSONObject passcfrdata;

// public static CfrDatass passcfrfield;

public static String getDateFromJson(String jsonDate) {
try {
jsonDate = jsonDate.substring(jsonDate.indexOf("(") + 1,
jsonDate.indexOf(")"));
Date time = new Date(Long.valueOf(jsonDate));
return ("" + dateformate.format(time));
} catch (Exception e) {
return "Date issue";
}
}

public static String getDateFromJsonSurvey(String jsonDate) {
try {
jsonDate = jsonDate.substring(jsonDate.indexOf("(") + 1,
jsonDate.indexOf(")"));
Date time = new Date(Long.valueOf(jsonDate));
return ("" + dateformatesurvey.format(time));
} catch (Exception e) {
return "Date issue";
}
}

public static String getwsDateJson(String jsonDate) {
try {
jsonDate = jsonDate.substring(jsonDate.indexOf("(") + 1,
jsonDate.indexOf(")"));
Date time = new Date(Long.valueOf(jsonDate));
return ("" + dateformate.format(time));
} catch (Exception e) {
jsonDate = "01 Jan 1990";

return jsonDate;
}
}

public static void DisplayAlert(String title, String message,
Context context) {

AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setTitle(title);
builder1.setMessage(message);
builder1.setCancelable(true);
builder1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();

}

public static void Displayprogress(Context context) {

dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

dialog.setContentView(R.layout.progressbarr);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);

dialog.show();

}





public static void Displayprogress_cfr(Context context) {

dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

dialog.setContentView(R.layout.progressbarr);

dialog.show();

}

public static void close_cfr_progress(Context context) {

dialog.dismiss();

}

public static void Displayprogress_download(Context context) {

dialog2 = new Dialog(context);
dialog2.requestWindowFeature(Window.FEATURE_NO_TITLE);

dialog2.setContentView(R.layout.progress_download);

dialog2.setCanceledOnTouchOutside(false);
dialog2.setCancelable(false);
dialog2.show();

}

public static void progressclose_download(Context context) {

dialog2.dismiss();

}

public static void Displayprogress1(Context context) {

dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

dialog.setContentView(R.layout.loadingemail);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);

dialog.show();

}

public static void progressclose(Context context) {

dialog.dismiss();

}

public static void ClearUserData(Context context) {
SharedPreferences sharedpreferences = context.getSharedPreferences(
MyPREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();

editor.clear();
editor.commit();
}

public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}

public static boolean isNetworkConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null)
return false;
else
return true;// return isInternetAvailable(context);
}

public static boolean isInternetAvailable(Context context) {
try {

HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(ConstantData.ServerUrl);
httppost.addHeader("Content-Type", "multipart/form-data");
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) {
return true;
}
} catch (Exception e) {
Log.i("exce", "" + e.toString());
}
return false;

}
}

database helper

package com.ibv.ibvfinance;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.IBinder;
import android.util.Log;

public class Databasehelper extends SQLiteOpenHelper {

private SQLiteDatabase myDataBase;
private final Context myContext;
private static final String DATABASE_NAME = "ibv";// "db.sqlite";
@SuppressLint("SdCardPath")
public final static String DATABASE_PATH = "/data/data/com.ibv.ibvfinance/databases/";
public static final int DATABASE_VERSION = 1;
private static final String TABAL_ibv = "ibvtb";

private static final String TABAL_goal = "goal";
private static final String TABAL_COUNTER = "counter";


@SuppressLint("SimpleDateFormat")
private SimpleDateFormat dateformate = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");

public Databasehelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.myContext = context;
}

// Create a empty database on the system
public void createDataBase() throws IOException {

boolean dbExist = checkDataBase();

if (dbExist) {
Log.v("DB Exists", "db exists");

} else {

this.getReadableDatabase();
try {
this.close();
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}

}

}

// Check database already exist or not
private boolean checkDataBase() {
boolean checkDB = false;
try {
String myPath = DATABASE_PATH + DATABASE_NAME;
File dbfile = new File(myPath);
checkDB = dbfile.exists();
} catch (SQLiteException e) {
System.out.println("delete database file.");
}
return checkDB;
}

// Copies your database from your local assets-folder to the just created
// empty database in the system folder
private void copyDataBase() throws IOException {

String outFileName = DATABASE_PATH + DATABASE_NAME;

OutputStream myOutput = new FileOutputStream(outFileName);
InputStream myInput = myContext.getAssets().open(DATABASE_NAME);

byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
}

// delete database
public void db_delete() {
File file = new File(DATABASE_PATH + DATABASE_NAME);
if (file.exists()) {
file.delete();
System.out.println("delete database file.");
}
}

// Open database
public void openDatabase() throws SQLException {
String myPath = DATABASE_PATH + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}

public synchronized void closeDataBase() throws SQLException {
if (myDataBase != null)
myDataBase.close();
super.close();
}

public boolean onSubmitForGcNo(HashMap<String, String> caclulatedData) {
return false;
}


public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
Log.v("Database Upgrade", "Database version higher than old.");
db_delete();
}
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub

}


//--------------chating function----

// --insert chating data to offline-----


public boolean Insert_Goal(String date , String time , String userid, String goal, String task)

{

String Quiry = "insert into "+ TABAL_ibv+ " (date , time , userid , goal , work) values ('"+date+"' , '"+time+"' , '"+userid+"' , '"+goal+"' , '"+task+"')";
try {

myDataBase.execSQL(Quiry);
Log.v("insert", "success");
return true;



} catch (Exception e) {
Log.v("insert error", ""+e.toString());
return false;

}


}


public void Insert_place(String place)

{

String Quiry = "insert into "+ TABAL_goal+ " (name) values ('"+place+"')";
try {

myDataBase.execSQL(Quiry);
Log.v("insert", "success place");


} catch (Exception e) {
Log.v("insert error place", ""+e.toString());

}

}


public void InsertCounter(int value)

{
int id = 1;
String Quiry = "insert into "+ TABAL_COUNTER+ " (id , value) values ('"+id+"','"+value+"',)";
try {

myDataBase.execSQL(Quiry);
Log.v("insert", "success");


} catch (Exception e) {
Log.v("insert error", ""+e.toString());

}

}


public void UpdateCounter(int value)

{

String Quiry = "Update "+ TABAL_COUNTER + " set value='"+value+"' WHERE id=1";

try {

myDataBase.execSQL(Quiry);
Log.v("insert", "success");


} catch (Exception e) {
Log.v("insert error", ""+e.toString());

}

}



public List<String> get_place()
{

String quiry = "Select * from "+TABAL_goal+ "";

List<String> goallist = new ArrayList<String>();

try {
Cursor cursor = myDataBase.rawQuery(quiry, null);
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
goallist.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}

} catch (Exception e) {
// TODO: handle exception
}

return goallist;

}


public List<Datatype> get_all_from_goalName(String goalname  ,String userid  ,String fromdt  ,String todt)
{
fromdt = "\'"+fromdt+"\'";
todt = "\'"+todt+"\'";

String quiry = "SELECT * FROM ibvtb WHERE goal='"+goalname +"' AND userid='"+userid +"' AND date BETWEEN "+fromdt+" AND "+todt+" order by id desc";


List<Datatype> goallist = new ArrayList<Datatype>();

try {
Cursor cursor = myDataBase.rawQuery(quiry, null);
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
Datatype d = new Datatype();
d.setDate_offline(cursor.getString(0));
d.setTime_offline(cursor.getString(1));
d.setGoal_offline(cursor.getString(3));
d.setWork_offline(cursor.getString(4));

goallist.add(d);
} while (cursor.moveToNext());
}
}

} catch (Exception e) {
// TODO: handle exception
}

return goallist;

}

public List<Datatype> get_all(String fromdt ,String todt , String userid )
{


fromdt = "\'"+fromdt+"\'";
todt = "\'"+todt+"\'";

String quiry = "SELECT * FROM ibvtb WHERE userid='"+userid +"' AND date BETWEEN "+fromdt+" AND "+todt+" order by id desc";


// String quiry = "Select * from "+TABAL_ibv+ "";

List<Datatype> goallist = new ArrayList<Datatype>();

try {
Cursor cursor = myDataBase.rawQuery(quiry, null);
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
Datatype d = new Datatype();
d.setDate_offline(cursor.getString(0));
d.setTime_offline(cursor.getString(1));
d.setGoal_offline(cursor.getString(3));
d.setWork_offline(cursor.getString(4));


goallist.add(d);
} while (cursor.moveToNext());
}
}

} catch (Exception e) {
// TODO: handle exception
}

return goallist;

}

public List<String> getcounter(String id)
{

String quiry = "Select * from "+TABAL_COUNTER+ " Where id='"+id+"'";

List<String> chatlist = new ArrayList<String>();

try {
Cursor cursor = myDataBase.rawQuery(quiry, null);
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
chatlist.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}

} catch (Exception e) {
// TODO: handle exception
}

return chatlist;

}







}

Saturday, 27 February 2016

profile changer




<a href='http://www.snapdeal.com/product/intex-fitrist-black-smart-watch/641203028585?utm_source=aff_prog&utm_campaign=afts&offer_id=17&aff_id=46976' target=_blank>Buy Intex Fitrist Smart Band - Black from Snapdeal</a>

Monday, 29 December 2014

//8th april=============

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceModel.Web;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace CYGNUS.Classes
{
    public class GCGeneralFuncations
    {
        string Connstr = System.Configuration.ConfigurationManager.ConnectionStrings["GCDefaultConnection"].ConnectionString;

        public DataTable getdatetablefromQuery(string Squery)
        {
            DataTable dataTable = new DataTable();

            dataTable.TableName = "datatable1";
            var conn = new SqlConnection(Connstr);

            using (var cmd = conn.CreateCommand())
            {

                cmd.CommandText = Squery;//
                SqlDataAdapter da = new SqlDataAdapter(cmd);

                conn.Close();
                // this will query your database and return the result to your datatable
                da.Fill(dataTable);

                da.Dispose();
                conn.Close();
            }

            return dataTable;
        }

        public DataTable GetDataTableFromSP(string Squery)
        {
            GCGeneralFuncations GCGF = new GCGeneralFuncations();

            DataTable dataTable = GCGF.getdatetablefromQuery(Squery);


            return dataTable;
        }

        public DataSet GetDataSetFromSP(string Squery)
        {
            GCGeneralFuncations GCGF = new GCGeneralFuncations();

            DataSet DS = GCGF.getdatasetfromQuery(Squery);


            return DS;
        }

        public DataSet getdatasetfromQuery(string Squery)
        {
            DataSet dataTable = new DataSet();
            // dataTable.TableName = "datatable1";
            var conn = new SqlConnection(Connstr);

            using (var cmd = conn.CreateCommand())
            {

                cmd.CommandText = Squery;//
                SqlDataAdapter da = new SqlDataAdapter(cmd);

                conn.Close();
                // this will query your database and return the result to your datatable
                da.Fill(dataTable);

                da.Dispose();
                conn.Close();
            }

            return dataTable;
        }

        public string StreamToJsonString(Stream jsonStream)
        {
            Encoding encoding = Encoding.UTF8;

            // Read the stream into a byte array
            byte[] data = ToByteArray(jsonStream);

            // Copy to a string for header parsing
            string content = encoding.GetString(data);

            // The first line should contain the delimiter
            int delimiterEndIndex = content.IndexOf("\r\n");

            if (delimiterEndIndex > -1)
            {
                string delimiter = content.Substring(0, content.IndexOf("\r\n"));


                content = content.Replace(delimiter, "");

                delimiter = content.Substring(0, content.IndexOf("\r\n\r\n"));

                content = content.Replace(delimiter, "").Replace("\r\n\r\n", "");


                delimiterEndIndex = content.IndexOf("------");
                content = content.Replace("--", "");


            }


            return content;

        }

        private byte[] ToByteArray(Stream stream)
        {
            byte[] buffer = new byte[32768];
            using (MemoryStream ms = new MemoryStream())
            {
                while (true)
                {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                        return ms.ToArray();
                    ms.Write(buffer, 0, read);
                }
            }
        }

        public List<T> DictionaryToObjectList<T>(object[] objArr) where T : new()
        {
            List<T> t = new List<T>();

            foreach (var itm in objArr)
            {
                T CMQ = DictionaryToObject<T>((Dictionary<string, object>)itm);
                t.Add(CMQ);
            }


            return t;
        }

        public T DictionaryToObject<T>(IDictionary<string, object> dict) where T : new()
        {
            T t = new T();
            PropertyInfo[] properties = t.GetType().GetProperties();
            int i = 0;
            foreach (PropertyInfo property in properties)
            {
                int j = i;
                if (!dict.Any(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase)))
                    continue;
                KeyValuePair<string, object> item = dict.First(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase));
                Type tPropertyType = t.GetType().GetProperty(property.Name).PropertyType;
                Type newT = Nullable.GetUnderlyingType(tPropertyType) ?? tPropertyType;
                if (item.Value != null)
                {
                    object newA = Convert.ChangeType(item.Value, newT);
                    t.GetType().GetProperty(property.Name).SetValue(t, newA, null);
                }

                i++;
            }
            return t;
        }

        public Stream ReturnJSONStream<T>(T t)
        {
            System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
            new System.Web.Script.Serialization.JavaScriptSerializer();
            string returnValue = jSearializer.Serialize(t);

            var jsonObj = new
            {
                Success = 1,
                Message = "",
                Response = t
            };

            JavaScriptSerializer jScriptSerializer = new JavaScriptSerializer();
            returnValue = jScriptSerializer.Serialize(jsonObj);

            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
            MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(returnValue));

            return memoryStream;
        }

        public string GetTypeInt(int Id)
        {
            string Type = "";

            if (Id == 0)
            {
                Type = "Add";
            }
            else
            {
                Type = "Edit";
            }

            return Type;
        }
    }
}



----------------------





ALTER Proc USP_InsertEnquiry_Tab

@EnquiryXml varchar(max),
@BRCD varchar(50),
@FinYear varchar(50)

as

BEGIN TRANSACTION              

DECLARE @hdoc1 int        
EXEC sp_xml_preparedocument @hdoc1 OUTPUT,@EnquiryXml              

declare @Message varchar(100), @Status int,@EnquiryNo varchar(50),@MobileNo varchar(50),@APKVersion varchar(50),
@DBAPKVersion varchar(50),@EnquiryCount int,@FromCity varchar(50),@ToCity varchar(50)

SELECT @Message='',@Status=0      


BEGIN TRY


SELECT @EnquiryNo=x.EnquiryNo,@MobileNo = x.MobileNo,@APKVersion=x.APKVersion,@FromCity=x.FromCity,@ToCity=x.ToCity   
FROM OPENXML(@hdoc1,'webx_cfr',2)                        
WITH                        
(                        
EnquiryNo VARCHAR(50) 'EnquiryNo',                        
MobileNo VARCHAR(50) 'MobileNo',
APKVersion VARCHAR(50) 'APKVersion',
FromCity VARCHAR(50) 'FromCity',
ToCity VARCHAR(50) 'ToCity'
)x                        
IF (@@ERROR <> 0) GOTO QuitWithRollback  


SELECT @EnquiryCount=COUNT(*) from Webx_Enquiry where EnquiryNo=@EnquiryNo              
IF (@@ERROR <> 0) GOTO QuitWithRollback                  
                
IF(@EnquiryCount!=0)                  
begin                  
                  
  Select @Status=0,@Message='Duplicate Enquiry No Find'                                                          
                  
  GOTO QuitWithRollback                  
                    
end   

SELECT Top 1 @DBAPKVersion=codedesc FROM Webx_Master_General where CodeType='Version'        
IF (@@ERROR <> 0) GOTO QuitWithRollback              
          
IF(@DBAPKVersion!=@APKVersion)        
begin      
 Select @Status=0,@Message='Please Update Your APK Version Contact APM Support Team.'                                                  
        
 GOTO QuitWithRollback         
end


CREATE TABLE #temp              
(              
 NextDocumentCode varchar(100) Collate Database_Default              
)              

IF (@@ERROR <> 0 ) GOTO QuitWithRollback    

INSERT INTO #temp EXEC WebX_SP_GetNextDocumentCode_Enq @BRCD, @FinYear,'ENQ'
IF (@@ERROR <> 0 ) GOTO QuitWithRollback    

                
Set @EnquiryNo = (Select NextDocumentCode FROM #temp)
IF (@@ERROR <> 0 ) GOTO QuitWithRollback

DROP TABLE #temp 
IF (@@ERROR <> 0 ) GOTO QuitWithRollback    

insert into Webx_Enquiry(
EnquiryNo,RegistrationDate,CallType,FromCity,ToCity,ToatlKM,OtherCity,PartyCode,PartyName,PersonName,Address1,
CityArea,PhoneNo,MobileNo,Pincode,EmailId,ReferenceBy,Movement,/*MovementDate,*/SurveyActivity,/*SurveyDate,*/SurveyTime,
Branch,FieldOfficer,DeskOfficer,/*RecallingDate,*/RecallingTime,EntryBy,EntryOn,COMPANY_CODE,Brcd,[Conversation],
EntryLoc,IsIVRyn,IVREntryBy,Designation,CustomerType,IsDistanceSurvey,APKVersion,IMEINumber,IsOffline,IsFromTab)

select @EnquiryNo,RegistrationDate,CallType,FromCity,ToCity,ToatlKM,OtherCity,PartyCode,PartyName,PersonName,Address1,
CityArea,PhoneNo,MobileNo,Pincode,EmailId,ReferenceBy,Movement,/*MovementDate,*/SurveyActivity,/*SurveyDate,*/SurveyTime,@BRCD,
FieldOfficer,DeskOfficer,/*RecallingDate,*/RecallingTime,EntryBy,EntryOn=Getdate(),'C004',Brcd,[Conversation],@BRCD,
IsIVRyn,IVREntryBy,Designation,CustomerType,IsDistanceSurvey ,APKVersion,IMEINumber,IsOffline,1
 
FROM OPENXML(@hdoc1, 'Webx_Enquiry', 2)     
WITH            
(      
RegistrationDate datetime 'RegistrationDate'
,CallType varchar(100) 'CallType'
,FromCity varchar(50) 'FromCity'
,ToCity varchar(50) 'ToCity'
,ToatlKM numeric(10,10) 'ToatlKM'
,OtherCity varchar(50) 'OtherCity'
,PartyCode varchar(50) 'PartyCode'
,PartyName VARCHAR(100) 'PartyName'
,PersonName varchar(100) 'PersonName'
,Address1 varchar(1000) 'Address1'
,CityArea varchar(200) 'CityArea'
,PhoneNo varchar(50) 'PhoneNo'
,MobileNo varchar(50) 'MobileNo'
,Pincode varchar(50) 'Pincode'
,EmailId varchar(50) 'EmailId'
,ReferenceBy varchar(50) 'ReferenceBy'
,Movement varchar(10) 'Movement'
--,MovementDate datetime 'MovementDate'
,SurveyActivity varchar(1) 'SurveyActivity'
--,SurveyDate datetime 'SurveyDate'
,SurveyTime varchar(10) 'SurveyTime'
--,Branch varchar(50) 'Branch'
,FieldOfficer varchar(50) 'FieldOfficer'
,DeskOfficer varchar(50) 'DeskOfficer'
--,RecallingDate datetime 'RecallingDate'
,RecallingTime varchar(10) 'RecallingTime'
,EntryBy varchar(50) 'EntryBy'
,Brcd varchar(20) 'Brcd'
,Conversation nvarchar 'Conversation'
--,EntryLoc varchar(50) 'EntryLoc'
,IsIVRyn varchar(1) 'IsIVRyn'
,IVREntryBy varchar(50) 'IVREntryBy'
,Designation varchar(100) 'Designation'
,CustomerType varchar(1) 'CustomerType'
,IsDistanceSurvey bit 'IsDistanceSurvey'
,APKVersion  VARCHAR(100) 'APKVersion'
,IMEINumber  VARCHAR(100) 'IMEINumber'    
,IsOffline  BIT 'IsOffline'    
)      
IF (@@ERROR <> 0 ) GOTO QuitWithRollback    

END TRY              

BEGIN CATCH              
 SELECT @Status=0,@Message='Error : '+ERROR_MESSAGE() +' At Line : '+ CONVERT(VARCHAR,ERROR_LINE())              
END CATCH

SELECT Status=@Status,Message=@Message,EnquiryNo=@EnquiryNo       
              
COMMIT TRANSACTION              
GOTO EndSave              
QuitWithRollback:              
IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION              
 SELECT Status=@Status,Message=@Message,EnquiryNo=@EnquiryNo     
EndSave: 

=============== 7th april ---------




var itemIndex = $("#Partialcontainer input.iHidden").length + 1;
                        <div class="col-md-12" id="Partialcontainer">
==========================
 public JsonResult CheckCityLocationMasters(int SrNo)
       {
           List<SelectListItem> list = new List<SelectListItem> { };
           try
           {
               List<CYGNUS_Master_City_Location_Mapping> CMLocation = new List<CYGNUS_Master_City_Location_Mapping>();
               CMLocation = CS.GetCityLocationObject(SrNo).ToList();
               int Count = CMLocation.Count;

               return new JsonResult()
               {
                   Data = new
                   {
                       Count = Count
                   }
               };

           }
           catch (Exception ex)
           {
               Error_Logs(ControllerName, "GetPincodeFromCityArea", "Json", "Listing", ex.Message);
               return Json(list);
           }
       }


===========================


public JsonResult GetStateFromCountry(int Country)
       {
           List<SelectListItem> list = new List<SelectListItem> { };
           try
           {
               DataTable Dt = CS.GetStateFromCountry(Country);
               List<GetCityFromCountry> Listing = DataRowToObject.CreateListFromTable<GetCityFromCountry>(Dt);

               return Json(Listing.OrderBy(c => c.Text), JsonRequestBehavior.AllowGet);
           }
           catch (Exception ex)
           {
               Error_Logs(ControllerName, "GetStateFromCountry", "Json", "Listing", ex.Message);
               return Json(list);
           }
       }




=======================



using System;
using System.Web.Mvc;
using System.Web;
using System.Collections.Generic;


namespace CYGNUS.Helpers
{
    public static class HtmlPrefixScopeExtensions
    {
        private const string idsToReuseKey = "__htmlPrefixScopeExtensions_IdsToReuse_";
        public static int prvcode=0;
        public static IDisposable BeginCollectionItem(this HtmlHelper html, string collectionName, string prefix)
        {
         
            // autocomplete="off" is needed to work around a very annoying Chrome behaviour whereby it reuses old values after the user clicks "Back", which causes the xyz.index and xyz[...] values to get out of sync.
            html.ViewContext.Writer.WriteLine(string.Format("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />", collectionName, html.Encode(prefix)));

            return BeginHtmlFieldPrefixScope(html, string.Format("{0}[{1}]", collectionName, prefix));
        }

        public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix)
        {
            return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix);
        }

        private static Queue<string> GetIdsToReuse(HttpContextBase httpContext, string collectionName)
        {
            // We need to use the same sequence of IDs following a server-side validation failure,
            // otherwise the framework won't render the validation error messages next to each item.
            string key = idsToReuseKey + collectionName;
            var queue = (Queue<string>)httpContext.Items[key];
            if (queue == null) {
                httpContext.Items[key] = queue = new Queue<string>();
                var previouslyUsedIds = httpContext.Request[collectionName + ".index"];
                if (!string.IsNullOrEmpty(previouslyUsedIds))
                    foreach (string previouslyUsedId in previouslyUsedIds.Split(','))
                        queue.Enqueue(previouslyUsedId);
            }
            return queue;
        }

        private class HtmlFieldPrefixScope : IDisposable
        {
            private readonly TemplateInfo templateInfo;
            private readonly string previousHtmlFieldPrefix;

            public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix)
            {
                this.templateInfo = templateInfo;

                previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
                templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
            }

            public void Dispose()
            {
                templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix;
            }
        }
    }
}
====================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Reflection;
using System.ComponentModel;

namespace CYGNUS.Classes
{
public class DataRowToObject
{
public static void SetItemFromRow<T>(T item, DataRow row)
where T : new()
{
// go through each column
foreach (DataColumn c in row.Table.Columns)
{
// find the property for the column
PropertyInfo p = item.GetType().GetProperty(c.ColumnName);

// if exists, set the value
if (p != null && row[c] != DBNull.Value)
{
p.SetValue(item, row[c], null);
}
}
}


public static T CreateItemFromRow<T>(DataRow row)
where T : new()
{
// create a new object
T item = new T();

// set the item
SetItemFromRow(item, row);

// return
return item;
}


public static List<T> CreateListFromTable<T>(DataTable tbl)
where T : new()
{
// define return list
List<T> lst = new List<T>();

// go through each row
foreach (DataRow r in tbl.Rows)
{
if (r[0] != "")
{
// add to the list
lst.Add(CreateItemFromRow<T>(r));
}
}

// return the list
return lst;
}


}
}

=====================================================================

      
CREATE proc [dbo].[USP_GetInsertDataProcedure]        
@TableName varchar(100)  ,      
@XMLPath varchar(100)  ,      
@varName varchar(100)        
as         
         
        
       
        
Declare @IdentityColumnName varchar(50),@GetXMLMappedColumnlist varchar(max),@Columnlist varchar(max),@SQRT varchar(max)        
  DECLARE @NewLineChar AS CHAR(2) = CHAR(13)      
        
select @GetXMLMappedColumnlist='',@Columnlist=''        
        
SELECT            
  @IdentityColumnName=       sys.columns.name        
FROM sys.columns JOIN sys.objects         
    ON sys.columns.object_id=sys.objects.object_id        
WHERE         
    sys.columns.is_identity=1        
    AND        
    sys.objects.type in (N'U') and sys.objects.name =@TableName        
            
        
Select @Columnlist=@Columnlist+(case when @Columnlist='' then '' else ',' end)+COLUMN_NAME,        
@GetXMLMappedColumnlist=@GetXMLMappedColumnlist+(case when @GetXMLMappedColumnlist='' then '' else ',' end)+COLUMN_NAME+ ' '+( case DATA_TYPE when 'numeric' then DATA_TYPE+'('+cast(Numeric_precision as varchar)+','+cast(Numeric_precision_RADIX as varchar)
  
    
      
+')'        
when 'varchar' then DATA_TYPE+'('+cast(CHARACTER_MAXIMUM_LENGTH as  varchar)+')'        
 else DATA_TYPE end)+' '+CHAR(39)+COLUMN_NAME+CHAR(39)  + CHAR(13) + CHAR(10)      
FROM   information_schema.columns        
WHERE  table_name = @TableName and COLUMN_NAME<>isnull(@IdentityColumnName,'')      
--ORDER  BY ordinal_position          
        
        
        
--select @Columnlist,@GetXMLMappedColumnlist  ,@IdentityColumnName      
        
        
select @SQRT='insert into '+@TableName+'('+@Columnlist+')       
 select '+@Columnlist+' FROM OPENXML(@'+@varName+', '''+@XMLPath+''', 2)         
WITH                
(          
'+@GetXMLMappedColumnlist+'        
)          
IF (@@ERROR <> 0 ) GOTO QuitWithRollback     '        
        
        
print @SQRT        
        
        















/*                              
Usp_GetEnquiryClosure_Listing '','EnquiryDate','26 Apr 14','26 Nov 14','23','ViewEdit','1'                              
*/                              
CREATE Proc Usp_GetEnquiryClosure_Listing                              
@EnquiryNo varchar(50),                              
@DateType varchar(50),                              
@FromDt Varchar(100),                              
@ToDt Varchar(100),                              
@Location varchar(100) ,                              
@ListingType varchar(100),                              
@CompanyID varchar(100)                              
                              
                              
as                              
                              
DECLARE @SQL VARCHAR(8000) ,@EnquiryNoCls varchar(600),@LocationCls varchar(600),@DateCls varchar(600),@ListingTypeCls varchar(2000),@CompanyIDCls varchar(2000)                              
select @EnquiryNoCls='' ,@LocationCls='' ,@DateCls='' , @ListingTypeCls='',@CompanyIDCls=''                              
                              
SELECT @DateCls =' AND convert(varchar,'+@DateType+',106) BETWEEN convert(DATETIME,' + CHAR(39) + @FromDt + CHAR(39) +',106) AND convert(DATETIME,' + CHAR(39) + @ToDt + CHAR(39) +',106) '                              
if @EnquiryNo<>''                              
begin                              
select @EnquiryNoCls='and EnquiryNo='+char(39)+@EnquiryNo+char(39) ,@DateCls=''                              
end                              
Declare @LocationCode varchar(50)                              
select @LocationCode =LocationCode from CYGNUS_Master_Location where Id=@Location                              
--select @LocationCode                              
if @LocationCode <>'HQTR'                              
begin                              
select @LocationCls='and Location='+char(39)+@Location+char(39)                              
end                              
                              
                              
if @CompanyID <>''                              
begin                              
select @CompanyIDCls='and CompanyCode='+char(39)+@CompanyID+char(39)                              
end                              
                              
if @ListingType ='Survey'                              
begin                              
select @ListingTypeCls='and SurveyActivity=3 and isnull(IsCancelled,0)=0'                              
end                              
else if @ListingType ='ViewEdit'                              
begin                              
select @ListingTypeCls=''                              
end                              
else if @ListingType ='Closure'                              
begin                              
select @ListingTypeCls='/*and SurveyActivity in (1,3)*/ and isnull(IsCancelled,0)=0'                              
end                              
else if @ListingType ='Cancellation'                              
begin                              
select @ListingTypeCls='and SurveyActivity not in (2) and isnull(IsCancelled,0)=0'                              
end                              
--select * from CYGNUS_Master_General where CodeType='SURVEY'                              
                              
                              
select @SQL='Select EnquiryNo, EnquiryDate,SurveyDate,AdditionalCity,PersonName,EmailID,(select LocationName from   CYGNUS_Master_Location where Id=Enq.Location ) as LocationName,Enq.Address,Enq.LandLineNo,Enq.TotalKM  ,Enq.Designation,(select   
CodeDesc FROM CYGNUS_Master_General where codetype=''DESIG'' AND CodeId=Enq.Designation) as DesignationName                           
,Location,SrNo,(SELECT top 1 Name from CYGNUS_Master_City where id=FromCity) as FromCityName,(SELECT top 1 Name from                               
CYGNUS_Master_City where id=ToCity) as ToCityName,SurveyActivityName=(SELECT top 1 CodeDesc from CYGNUS_Master_General                               
where CodeType=''SURVEY'' and CodeId=SurveyActivity)+(case when SurveyActivity=''2'' then '' (''+isnull(QuotationNo,'''') +'')'' else '''' end)                              
,(SELECT top 1 UserName from CYGNUS_Master_Users where userid=FieldOfficer)                               
as FieldOfficerName,SurveyActivity,(SELECT top 1 UserName from CYGNUS_Master_Users where userid=DeskOfficer) as DescOfficerOfficerName,Conversation=(select top 1 cn.Conversation from CYGNUS_Master_Enquiry_Conversation cn where Enq.SrNo=cn.EnquiryID order 
  
    
by cn.EntryDate desc)  ,                              
isnull(IsCancelled,0) as IsCancelled  ,IsServeyDone,ServeyID ,QuotationNo,Enq.MobileNo                    
,PartyName=(select cust.CustomerName from CYGNUS_Master_Customer cust where cust.CustomerID=PartyCode)                           
FROM CYGNUS_Master_Enquiry Enq WITH(NOLOCK) where 1=1 and Enq.CallType=1 '+@DateCls+@EnquiryNoCls+@LocationCls+@ListingTypeCls+@CompanyIDCls+' AND (Enq.QuotationID IS NULL OR  Enq.QuotationNo IS NULL) '                              
                              
Exec (@SQL)                              
select @SQL 






















CREATE Proc [dbo].[Usp_Insert_CityMaster]    
@CityId varchar(100),    
@CityInsertXML varchar(2000)    
    
as    
DECLARE @Status int, @Message VARCHAR(200)    
select @Message='',@Status=0    
declare @hdoc1 int    
EXEC sp_xml_preparedocument @hdoc1 OUTPUT, @CityInsertXML    
    
--select * from CYGNUS_Master_City    
if @CityId = 0    
BEGIN TRY    
begin    
--select * from CYGNUS_Master_City    
Insert into CYGNUS_Master_City(Name,Region,State,IsPermit,IsODA,ODAKm,IsActive,EntryBy,EntryDate,CompanyID,Country)    
SELECT    
Name,Region,State,IsPermit,IsODA,ODAKm,IsActive,Entryby,GETDATE(),CompanyID  ,Country  
FROM OPENXML(@hdoc1, 'DocumentElement', 2)    
WITH    
(    
Name varchar(50) 'Name',    
Region Varchar(50) 'Region',    
State int 'State',    
IsPermit bit 'IsPermit' ,    
IsODA bit 'IsODA',    
ODAKm numeric(18,0) 'ODAKm',    
IsActive bit 'IsActive',    
Entryby varchar(50) 'EntryBy' ,    
CompanyID int 'CompanyID'    
,Country int 'Country'  
)    
end    
SELECT @Status=1,@Message='Done'    
END TRY    
    
BEGIN CATCH    
--select 'Hii'    
SELECT @Status=0,@Message='Error : '+ERROR_MESSAGE() +' At Line : '+ CONVERT(VARCHAR,ERROR_LINE())    
insert into CYGNUS_Error_History(ModuleName,TransactionType,ErrorMessage) select 'City Master','Insert',@Message    
    
END CATCH    
else if @CityId>0    
BEGIN TRY    
begin    
    
update CYGNUS_Master_City set Name=T.Name,Region=T.Region,State= T.State,IsPermit=T.IsPermit,IsODA=T.IsODA, ODAKm=T.ODAKm,IsActive=T.IsActive,UpdatedBy=T.UpdatedBy,UpdatedDate=GETDATE(),CompanyID=T.CompanyID,Country=T.Country from (    
SELECT Name,Region,State,IsPermit,IsODA,ODAKm,IsActive,UpdatedBy,CompanyID,Country  
FROM OPENXML(@hdoc1, 'DocumentElement', 2)    
WITH    
(    
Name varchar(50) 'Name',    
Region Varchar(50) 'Region',    
State int 'State',    
IsPermit bit 'IsPermit' ,    
IsODA bit 'IsODA',    
ODAKm numeric(18,0) 'ODAKm',    
IsActive bit 'IsActive',    
UpdatedBy varchar(50) 'UpdatedBy',    
CompanyID int 'CompanyID'    
,Country int 'Country'  
)    
)T    
    
where Id=@CityId    
    
SELECT @Status=1,@Message='Done'    
end    
END TRY    
    
BEGIN CATCH    
SELECT @Status=0,@Message='Error : '+ERROR_MESSAGE() +' At Line : '+ CONVERT(VARCHAR,ERROR_LINE())    
insert into CYGNUS_Error_History(ModuleName,TransactionType,ErrorMessage) select 'City Master','Update',@Message    
END CATCH    
    
    
SELECT TranXaction=@Message,Status=@Status    
    

EXEC ts_Add_Patch_History '140819_Usp_Insert_CityMaster.sql',1 


//----------------------------------------------------------new ----------------------------------


@using (Html.BeginCollectionItem("CFRList", Model.CFRID.ToString()))