Esempio n. 1
1
    private static void SignIn(string loginName, object userData)
    {
        var jser = new JavaScriptSerializer();
        var data = jser.Serialize(userData);

        //创建一个FormsAuthenticationTicket,它包含登录名以及额外的用户数据。
        var ticket = new FormsAuthenticationTicket(2,
            loginName, DateTime.Now, DateTime.Now.AddDays(1), true, data);

        //加密Ticket,变成一个加密的字符串。
        var cookieValue = FormsAuthentication.Encrypt(ticket);

        //根据加密结果创建登录Cookie
        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue)
        {
            HttpOnly = true,
            Secure = FormsAuthentication.RequireSSL,
            Domain = FormsAuthentication.CookieDomain,
            Path = FormsAuthentication.FormsCookiePath
        };
        //在配置文件里读取Cookie保存的时间
        double expireHours = Convert.ToDouble(ConfigurationManager.AppSettings["loginExpireHours"]);
        if (expireHours > 0)
            cookie.Expires = DateTime.Now.AddHours(expireHours);

        var context = System.Web.HttpContext.Current;
        if (context == null)
            throw new InvalidOperationException();

        //写登录Cookie
        context.Response.Cookies.Remove(cookie.Name);
        context.Response.Cookies.Add(cookie);
    }
        public void Should_register_converters_when_asked()
        {
            // Given
            var defaultSerializer = new JavaScriptSerializer();
            var configuration = new JsonConfiguration(Encoding.UTF8, new[] { new TestConverter() }, new[] { new TestPrimitiveConverter() }, false, false);

            // When
            var serializer = new JavaScriptSerializer(configuration, true, GlobalizationConfiguration.Default);

            var data =
                new TestData()
                {
                    ConverterData =
                        new TestConverterType()
                        {
                            Data = 42,
                        },

                    PrimitiveConverterData =
                        new TestPrimitiveConverterType()
                        {
                            Data = 1701,
                        },
                };

            const string ExpectedJSON = @"{""converterData"":{""dataValue"":42},""primitiveConverterData"":1701}";

            // Then
            serializer.Serialize(data).ShouldEqual(ExpectedJSON);

            serializer.Deserialize<TestData>(ExpectedJSON).ShouldEqual(data);
        }
Esempio n. 3
0
    private void InitForm()
    {
        string query = Helpers.GetQueryString("query");
        JavaScriptSerializer json = new JavaScriptSerializer();
        List<SearchResult> searchResults = null;
        if (query != "")
        {
            //TODO: User query instead
            //searchResults = SearchResultService.GetSearchResultsFromRepository(query, 50);\
            double latitude = 45.117374, longitude = -93.215287;

            searchResults = SearchResultService.GetSearchResultsFromRepository(latitude, longitude, 50);
            litTitle.Text = string.Format("<h1 class='resultsnear'>Results for Child Care Centers near \"{0}\"</h1>", Xss.HtmlEncode(query));
            gvSearchResults.DataSource = searchResults;
            gvSearchResults.DataBind();
            _searchResults = json.Serialize(new
            {
                query = query,
                results = searchResults
            });
        }
        else
        {
            _searchResults = json.Serialize(new
            {
                query = "",
                results = searchResults
            });
        }
    }
 public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
 {
     return new Dictionary<string, object>
     {
         {"serializedValue", obj}
     };
 }
Esempio n. 5
0
 //will attempt to serialize an object of any type
 public static Response SerializeToJsonResponse(dynamic input)
 {
     Nancy.Json.JavaScriptSerializer ser = new JavaScriptSerializer();
     var response = (Response)ser.Serialize(input);
     response.ContentType = "application/json";
     return response;
 }
 public void ProcessRequest(HttpContext context)
 {
     MoSmsResp moSmsResp = null;
     string jsonString="";
     context.Response.ContentType = "application/json";
     try
     {
         byte[] PostData = context.Request.BinaryRead(context.Request.ContentLength);
         jsonString = Encoding.UTF8.GetString(PostData);
         JavaScriptSerializer json_serializer = new JavaScriptSerializer();
         MoSmsReq moSmsReq = json_serializer.Deserialize<MoSmsReq>(jsonString);
         moSmsResp = GenerateStatus(true);
         onMessage(moSmsReq);
     }
     catch (Exception)
     {
         moSmsResp = GenerateStatus(false);
     }
     finally
     {
         if (jsonString.Equals(""))
             context.Response.Write(APPLICATION_RUNING_MESSAGE);
         else
             context.Response.Write(moSmsResp.ToString());
     }
 }
Esempio n. 7
0
    void GetData()
    {
        IList<object> list = new List<object>();
        for (var i = 0; i < 5; i++)
        {
            list.Add(new
            {
                id = i, 
                pid = -1,
                name = "部门" + i,
                date = DateTime.Now,
                remark = "部门" + i + " 备注" 
            });
        }

        for (var i = 5; i < 10; i++)
        {
            list.Add(new
            {
                id = i,
                pid = 1,
                name = "部门1-" + i,
                date = DateTime.Now 
            });
        } 

        var griddata = new { Rows = list };
        string s = new JavaScriptSerializer().Serialize(griddata);
        Response.Write(s);
    }
Esempio n. 8
0
 public string GetJsonBySend(string sCity, string sArea)
 {
     JavaScriptSerializer serializer = new JavaScriptSerializer();
     DataSet ds = new DataSet();
     string sqlstr = string.Format(@"
         Select
             pid,pNam,plit [lat],plng [lng],p成交價,
             Case
                 When p型態 In (N'電梯大樓',N'無電梯公寓',N'辦公商業大樓',N'套房') Then N'寓'
                 When p型態 In (N'廠辦',N'別墅',N'透天',N'其他',N'店面') Then N'透'
                 else N'土'
             End p型態
         From SellList Where PCity = N'{0}' And PArea = N'{1}' And Plit <> '0'  ", sCity, sArea);
     using (SqlConnection cn = new SqlConnection(sidebar.ConnString))
     {
         if (cn.State != ConnectionState.Open) cn.Open();
         using (SqlCommand cm = new SqlCommand(sqlstr, cn))
         {
             using (SqlDataAdapter da = new SqlDataAdapter(cm))
             {
                 da.Fill(ds);
             }
         }
     }
     return JsonConvert.SerializeObject(ds.Tables[0], Formatting.Indented);
 }
Esempio n. 9
0
 public static string ObtenerUnidadNegocio()
 {
     List<List<EntUnidadNegocio>> multilst = new BusQueja().ObtenerUnidadNegocio();
     JavaScriptSerializer oSerializer = new JavaScriptSerializer();
     string sJSON = oSerializer.Serialize(multilst);
     return sJSON;
 }
Esempio n. 10
0
 public static string student_info()
 {
     JavaScriptSerializer jss = new JavaScriptSerializer();
     stu_Manage stuManage = new stu_Manage();
     return jss.Serialize(stuManage.stu_Info(sno));
     //return string.Format("欢迎你{0} {1}", sno, sname);
 }
Esempio n. 11
0
        public void Should_not_register_converters_when_not_asked()
        {
            // Given
            var defaultSerializer = new JavaScriptSerializer();

            // When
            var serializer = new JavaScriptSerializer(JsonConfiguration.Default, GlobalizationConfiguration.Default);

            var data =
                new TestData()
                {
                    ConverterData =
                        new TestConverterType()
                        {
                            Data = 42,
                        },

                    PrimitiveConverterData =
                        new TestPrimitiveConverterType()
                        {
                            Data = 1701,
                        },
                };

            const string ExpectedJSON = @"{""converterData"":{""data"":42},""primitiveConverterData"":{""data"":1701}}";

            // Then
            serializer.Serialize(data).ShouldEqual(ExpectedJSON);

            serializer.Deserialize<TestData>(ExpectedJSON).ShouldEqual(data);
        }
Esempio n. 12
0
 public static string teacher_info()
 {
     JavaScriptSerializer jss = new JavaScriptSerializer();
     tea_Manage teaManage = new tea_Manage();
     return jss.Serialize(teaManage.tea_Info(tno));
     //return string.Format("欢迎你{0} {1}", sno, sname);
 }
Esempio n. 13
0
    public string GetTasks()
    {
        IList<Task> tasks = new List<Task>();

        using(SqlConnection connection = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|JonteDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True") )
        {
            using (SqlCommand command = new SqlCommand("SELECT * FROM Tasks",connection))
            {
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Task task = new Task();
                    task.ID = (int)reader["TaskID"];
                    task.Name = (string)reader["Name"];
                    task.Author = (string) reader["Author"];
                    task.Done = (bool) reader["Done"];
                    tasks.Add(task);
                }
            }
        }

        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return serializer.Serialize(tasks);
    }
Esempio n. 14
0
 protected void WriteResponseJSON(object response)
 {
     Response.Clear();
     Response.ContentType = "application/json";
     var jss = new JavaScriptSerializer();
     Response.Write(jss.Serialize(response));
 }
Esempio n. 15
0
    private static Dictionary<string, string> ParsePayload(string[] args)
    {
        int payloadIndex=-1;
         for (var i = 0; i < args.Length; i++)
            {
                Console.WriteLine(args[i]);
                if (args[i]=="-payload")
                 {
                    payloadIndex = i;
                    break;
                 }
            }
         if (payloadIndex == -1)
        {
           Console.WriteLine("Payload is empty");
           Environment.Exit(0);
        }

         if (payloadIndex >= args.Length-1)
        {
            Console.WriteLine("No payload value");
            Environment.Exit(0);
        }

         string json = File.ReadAllText(args[payloadIndex+1]);
         var jss = new JavaScriptSerializer();
         Dictionary<string, string> values = jss.Deserialize<Dictionary<string, string>>(json);
         return values;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Admin"] == null || Session["Admin"].ToString() != "1")
            Response.Redirect("login.aspx");
        if (Request.QueryString["id"] == null)
            Response.Redirect("AboutListing.aspx");
        id = Request.QueryString["id"].ToString();

        PageHeader = Util.GetTemplate("Admin_header");
        string json = Util.GetFileContent("data");
        var serializer = new JavaScriptSerializer();
        serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
        obj = serializer.Deserialize(json, typeof(object));

        if (!IsPostBack)
        {
            bool exists = false;
            foreach (dynamic obj1 in obj["Portfolio"])
            {
                if (obj1["id"] == id)
                {
                    txtTitle.Text = obj1["title"];
                    txtDescription.Text = obj1["description"];
                    txtSiteLink.Text = obj1["sitelink"];
                    txtClient.Text = obj1["client"];
                    txtDate.Text = obj1["date"];
                    txtService.Text = obj1["service"];
                    imgImage.ImageUrl = "../" + obj1["image"];
                    exists = true;
                }
            }
            if(!exists)
                Response.Redirect("PortfolioListing.aspx");
        }
    }
Esempio n. 17
0
 public void parseJson(String HtmlResult)
 {
     var serializer = new JavaScriptSerializer();
     serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
     dynamic obj = serializer.Deserialize(HtmlResult, typeof(object));
     Console.WriteLine(obj.meta);
 }
Esempio n. 18
0
File: Json.cs Progetto: slai/cwkb
        public static object Deserialize(string input, JavaScriptSerializer jss)
        {
            if (jss == null)
                throw new ArgumentNullException ("jss");

            return Deserialize (new StringReader (input), jss);
        }
    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        if (dictionary == null)
            throw new ArgumentNullException("dictionary");

        return type == typeof(object) ? new DynamicJsonObject(dictionary) : null;
    }
Esempio n. 20
0
 public static dynamic GEOCodeAddress(String Address)
 {
     var address = String.Format("http://maps.google.com/maps/api/geocode/json?address={0}&sensor=false", Address.Replace(" ", "+"));
     var result = new System.Net.WebClient().DownloadString(address);
     var jss = new JavaScriptSerializer();
     return jss.Deserialize<dynamic>(result);
 }
Esempio n. 21
0
    protected void Page_Load(object sender, EventArgs e)
    {
        String str = HttpContext.Current.Request.Url.AbsoluteUri;
        String userId = str.Substring(str.LastIndexOf("=")+1);
        try
        {
            String filename = Server.MapPath("~/User_Data/" + userId + ".js");
            String jsonData = File.ReadAllText(filename);

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            RegData data = serializer.Deserialize<RegData>(jsonData);

            name.Text = data.name;
            userid.Text = userId;

            String imageurl = "~/User_Images/" + userId + ".jpg";
            userImage.ImageUrl = imageurl;


        }
        catch (IOException exn)
        {
            Response.Redirect("Error.aspx?userid=" + userId + "&errid=lookup");
        }
    }
 // Methods
 private static void AddItemToList(IList oldList, IList newList, Type elementType, JavaScriptSerializer serializer)
 {
     foreach (object obj2 in oldList)
     {
         newList.Add(ConvertObjectToType(obj2, elementType, serializer));
     }
 }
 private static void AssignToPropertyOrField(object propertyValue, object o, string memberName, JavaScriptSerializer serializer)
 {
     IDictionary dictionary = o as IDictionary;
     if (dictionary != null)
     {
         propertyValue = ConvertObjectToType(propertyValue, null, serializer);
         dictionary[memberName] = propertyValue;
     }
     else
     {
         Type type = o.GetType();
         PropertyInfo property = type.GetProperty(memberName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
         if (property != null)
         {
             MethodInfo setMethod = property.GetSetMethod();
             if (setMethod != null)
             {
                 propertyValue = ConvertObjectToType(propertyValue, property.PropertyType, serializer);
                 setMethod.Invoke(o, new object[] { propertyValue });
                 return;
             }
         }
         FieldInfo field = type.GetField(memberName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
         if (field != null)
         {
             propertyValue = ConvertObjectToType(propertyValue, field.FieldType, serializer);
             field.SetValue(o, propertyValue);
         }
     }
 }
 public void GetServiceItemSetting()
 {
     AspxCommonInfo aspxCommonObj = new AspxCommonInfo();
     aspxCommonObj.StoreID = StoreID;
     aspxCommonObj.PortalID = PortalID;
     aspxCommonObj.CultureName = CultureName;
     ServiceItemController objService = new ServiceItemController();
     JavaScriptSerializer json_serializer = new JavaScriptSerializer();
     List<ServiceItemSettingInfo> lstServiceSetting = objService.GetServiceItemSetting(aspxCommonObj);
     if (lstServiceSetting != null && lstServiceSetting.Count > 0)
     {
         foreach (var serviceSetting in lstServiceSetting)
         {
             object obj = new
             {
                 IsEnableService = serviceSetting.IsEnableService,
                 ServiceCategoryInARow = serviceSetting.ServiceCategoryInARow,
                 ServiceCategoryCount = serviceSetting.ServiceCategoryCount,
                 IsEnableServiceRss = serviceSetting.IsEnableServiceRss,
                 ServiceRssCount = serviceSetting.ServiceRssCount,
                 ServiceRssPage = serviceSetting.ServiceRssPage,
                 ServiceDetailsPage = serviceSetting.ServiceDetailsPage,
                 ServiceItemDetailPage = serviceSetting.ServiceItemDetailsPage,
                 BookAnAppointmentPage = serviceSetting.BookAnAppointmentPage,
                 AppointmentSuccessPage = serviceSetting.AppointmentSuccessPage
             };
             Settings = json_serializer.Serialize(obj);
         }
     }
 }
Esempio n. 25
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            XDocument doc = null;
            string result = null;
            if (Request.QueryString["mode"] != null)
            {
                JavaScriptSerializer serializer = null;
                doc = XDocument.Load(Server.MapPath("~/App_Data/Links.xml"));
                switch (Request.QueryString["mode"])
                {
                    case "1": // Load list
                        serializer = new JavaScriptSerializer();
                        var list = doc.Element("Links").Elements("Link").Select(lk => new { Id = lk.Attribute("id").Value, Title = lk.Element("Title").Value, Target = lk.Element("Target").Value });
                        result = serializer.Serialize(list);
                        break;

                    case "2": // Load a link
                        serializer = new JavaScriptSerializer();
                        var test = doc.Element("Links").Elements("Link").Where(lk => lk.Attribute("id").Value == Request.QueryString["id"]).Select(lk => new { Title = lk.Element("Title").Value, Target = lk.Element("Target").Value });
                        result = serializer.Serialize(test);
                        break;
                }

                Response.Clear();
                Response.Write(result);
                Response.End();
            }
            else if (Request.QueryString["id"] != null)
            {
                doc = XDocument.Load(Server.MapPath("~/App_Data/Links.xml"));
                if (Request.QueryString["id"] == "0") // Add mode
                {
                    string maxId = doc.Element("Links").Elements("Link").Max(tst => tst.Attribute("id").Value);

                    doc.Element("Links").Add(new XElement("Link", new XAttribute("id", maxId == null ? "1" : (short.Parse(maxId) + 1).ToString()),
                                                       new XElement("Title", Request.QueryString["tle"]),
                                                       new XElement("Target", Request.QueryString["trg"])));
                    doc.Save(Server.MapPath("~/App_Data/Links.xml"));
                    result = "1";
                }
                else // Edit mode
                {
                    IEnumerable<XElement> element = doc.Element("Links").Elements("Link").Where(an => an.Attribute("id").Value == Request.QueryString["id"]);
                    foreach (XElement item in element)
                    {
                        item.Element("Title").Value = Request.QueryString["tle"];
                        item.Element("Target").Value = Request.QueryString["trg"];
                        doc.Save(Server.MapPath("~/App_Data/Links.xml"));
                        result = "1";
                    }
                }

                Response.Clear();
                Response.Write(result);
                Response.End();
            }
        }
    }
 private void GetMegaCategorySetting()
 {
     AspxCommonInfo aspxCommonObj = new AspxCommonInfo();
     aspxCommonObj.StoreID = GetStoreID;
     aspxCommonObj.PortalID = GetPortalID;
     aspxCommonObj.CultureName = GetCurrentCultureName;
     JavaScriptSerializer json_serializer = new JavaScriptSerializer();
     MegaCategoryController objCat = new MegaCategoryController();
     MegaCategorySettingInfo megaCatSetting = objCat.GetMegaCategorySetting(aspxCommonObj);
     if (megaCatSetting != null)
     {
         object obj = new {
         ModeOfView = megaCatSetting.ModeOfView,
         NoOfColumn = megaCatSetting.NoOfColumn,
         ShowCatImage = megaCatSetting.ShowCategoryImage,
         ShowSubCatImage = megaCatSetting.ShowSubCategoryImage,
         Speed = megaCatSetting.Speed,
         Effect = megaCatSetting.Effect,
         EventMega = megaCatSetting.EventMega,
         Direction = megaCatSetting.Direction,
         MegaModulePath = MegaModulePath
     };
         Settings = json_serializer.Serialize(obj); 
     }
 }
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (string.IsNullOrEmpty(this.ContentType))
        {
            response.ContentType = this.ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }

        if (this.ContentEncoding != null)
        {
            response.ContentEncoding = this.ContentEncoding;
        }

        if (this.Data != null)
        {
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            string jsonString = jsSerializer.Serialize(Data);
            MatchEvaluator matchEvaluator = new MatchEvaluator(this.ConvertJsonDateToDateString);
            Regex reg = new Regex(@"\\/Date\((\d+)\)\\/");
            jsonString = reg.Replace(jsonString, matchEvaluator);
            response.Write(jsonString);
        }
    }
    /// <summary>
    /// The ConvertTourDataTableTOJson method converts a filled data table into a
    /// JSON string to be saved as a text file by the caller.
    /// </summary>
    public string CovertCategoryDataTableToJSON(DataTable parFilledDataTable)
    {
        //Convert DataTable to List collection of Transfer Objects
        List<TO_POI_Cateogry> items = new List<TO_POI_Cateogry>();

        foreach (DataRow row in parFilledDataTable.Rows)
        {
            string ID = Convert.ToString(row["Category_Code"]);
            string title = Convert.ToString(row["Category_Name"]);
            string fileName = "Category_" + ID + ".js";

            TO_POI_Cateogry itemTransferObject = new TO_POI_Cateogry(ID, title, fileName);
            items.Add(itemTransferObject);
        }

        //Create JSON-formatted string
        JavaScriptSerializer oSerializer = new JavaScriptSerializer();
        string JSONString = oSerializer.Serialize(items);
        
        //add in return JSONString when taking out PrettyPrint
        return JSONString;

        ////Format json string
        //string formattedJSONString = JsonFormatter.PrettyPrint(JSONString);

       // return formattedJSONString;
    }
    /// <summary>
    /// Create startup script
    /// </summary>
    private string GetStartupScript()
    {
        JavaScriptSerializer sr = new JavaScriptSerializer();
        string json = sr.Serialize(
            new
            {
                headerIconId = headerIcon.ClientID,
                btnLoginId = btnLogin.ClientID,
                btnLoginShortcutId = btnLoginShortcut.ClientID,
                btnLogoutId = btnLogout.ClientID,
                btnSettingsId = btnSettings.ClientID,
                loginShortcutWrapperId = loginShortcutWrapper.ClientID,
                lblNotificationNumberId = lblNotificationNumber.ClientID,
                ulActiveRequestsId = ulActiveRequests.ClientID,
                ulNewRequestsId = ulNewRequests.ClientID,
                lnkNewRequestsId = lnkNewRequests.ClientID,
                lblNewRequestsId = lblNewRequests.ClientID,

                resRoomNewMessagesFormat = ResHelper.GetString("chat.support.roomnewmessages"),
                resNewRequestsSingular = ResHelper.GetString("chat.support.newrequestssingular"),
                resNewRequestsPlural = ResHelper.GetString("chat.support.newrequestsplural"),

                settingsUrl = URLHelper.GetAbsoluteUrl("~/CMSModules/Chat/Pages/ChatSupportSettings.aspx"),
                notificationManagerOptions = new
                {
                    soundFileRequest = ChatHelper.EnableSoundSupportChat ? ResolveUrl("~/CMSModules/Chat/CMSPages/Sound/Chat_notification.mp3") : String.Empty,
                    soundFileMessage = ChatHelper.EnableSoundSupportChat ? ResolveUrl("~/CMSModules/Chat/CMSPages/Sound/Chat_message.mp3") : String.Empty,
                    notifyTitle = ResHelper.GetString("chat.general.newmessages")
                }
            }
        );

        return String.Format("$cmsj(function (){{ new ChatSupportHeader({0}); }});", json);
    }
Esempio n. 30
0
    public string GetUserInfo(string username, string password)
    {
        User user = new User();
        using (MySqlConnection conn = new MySqlConnection(Tools.connectionString()))
        {
            conn.Open();
            MySqlCommand cmd = new MySqlCommand("GetUserInfo",conn);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("_userid", DBNull.Value);
            cmd.Parameters.AddWithValue("_username", username);
            cmd.Parameters.AddWithValue("_password", password);

            MySqlDataReader reader = cmd.ExecuteReader();

            if(reader.Read())
            {
                user.UserID = Convert.ToInt32(reader["UserID"]);
                user.UserName = reader["UserName"].ToString();
                user.Wallet.Amount = Convert.ToDouble(reader["Amount"]);
                user.Wallet.Refills = Convert.ToInt32(reader["Refills"]);
            }
        }

        JavaScriptSerializer js = new JavaScriptSerializer();
        string strJSON = js.Serialize(user);
        return strJSON;
    }
Esempio n. 31
0
        /// <summary>
        ///  USE JavaScriptSerializer
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T FromJson<T>(string json)
        {
            var serializer = new JavaScriptSerializer();

            return serializer.Deserialize<T>(json);
        }
Esempio n. 32
0
        void GetChunk()
        {
            using (WebClient client = new WebClient())
            {
                string token = client.DownloadString(
                    String.Format("{0}/consumer/{1}/{2}/{3}/0/token", Server + "/observer-mode/rest",
                                  "getLastChunkInfo",
                                  Region,
                                  GameId));

                JavaScriptSerializer        serializer       = new JavaScriptSerializer();
                Dictionary <string, object> deserializedJSON = serializer.Deserialize <Dictionary <string, object> >(token);

                int ChunkId = Convert.ToInt32(deserializedJSON["chunkId"]);
                if (ChunkId == 0)
                {
                    //Try get chunk once avaliable
                    return;
                }

                if (LastChunkNumber == ChunkId)
                {
                    //Sometimes chunk 1 isn't retrieved so get it again... it's like 7 kb so np
                    client.DownloadFile(
                        String.Format("{0}/consumer/{1}/{2}/{3}/{4}/token", Server + "/observer-mode/rest",
                                      "getGameDataChunk",
                                      Region,
                                      GameId,
                                      1),
                        Path.Combine("cabinet", GameId + "-" + Region, "chunk-" + 1));

                    client.DownloadFile(
                        String.Format("{0}/consumer/{1}/{2}/{3}/token", Server + "/observer-mode/rest",
                                      "endOfGameStats",
                                      Region,
                                      GameId),
                        Path.Combine("cabinet", GameId + "-" + Region, "endOfGameStats"));

                    if (OnReplayRecorded != null)
                    {
                        OnReplayRecorded();
                    }

                    Recording = false;
                    return;
                }

                //Get keyframe
                if (ChunkId % 2 == 0)
                {
                    int KeyFrameId = Convert.ToInt32(deserializedJSON["keyFrameId"]);
                    if (KeyFrameId != 0)
                    {
                        client.DownloadFile(
                            String.Format("{0}/consumer/{1}/{2}/{3}/{4}/token", Server + "/observer-mode/rest",
                                          "getKeyFrame",
                                          Region,
                                          GameId,
                                          KeyFrameId),
                            Path.Combine("cabinet", GameId + "-" + Region, "key-" + KeyFrameId));
                    }
                }

                client.DownloadFile(
                    String.Format("{0}/consumer/{1}/{2}/{3}/{4}/token", Server + "/observer-mode/rest",
                                  "getGameDataChunk",
                                  Region,
                                  GameId,
                                  ChunkId),
                    Path.Combine("cabinet", GameId + "-" + Region, "chunk-" + ChunkId));

                if (OnGotChunk != null)
                {
                    OnGotChunk(ChunkId);
                }

                LastChunkNumber = ChunkId;

                Thread.Sleep(Convert.ToInt32(deserializedJSON["nextAvailableChunk"]));
            }
        }
Esempio n. 33
0
        public static List <GetSoftware> GetCatalog(string customerid = "")
        {
            if (string.IsNullOrEmpty(customerid))
            {
                if (File.Exists(Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), "rzcat.json"))) //Cached content exists
                {
                    try
                    {
                        DateTime dCreationDate = File.GetLastWriteTime(Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), "rzcat.json"));
                        if ((DateTime.Now - dCreationDate) < new TimeSpan(0, 30, 0)) //Cache for 30min
                        {
                            //return cached Content
                            string jRes = File.ReadAllText(Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), "rzcat.json"));
                            JavaScriptSerializer ser  = new JavaScriptSerializer();
                            List <GetSoftware>   lRes = ser.Deserialize <List <GetSoftware> >(jRes);
                            return(lRes);
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("E1" + ex.Message, "GetCatalog");
                    }
                }
            }

            try
            {
                sURL = "UDP"; //reset URL as this part is only called every 30 min

                Task <string> response;
                if (string.IsNullOrEmpty(customerid))
                {
                    response = oClient.GetStringAsync(sURL + "/rest/v2/GetCatalog");
                }
                else
                {
                    response = oClient.GetStringAsync(sURL + "/rest/v2/GetCatalog?customerid=" + customerid);
                }

                response.Wait(60000); //60s max

                if (response.IsCompleted)
                {
                    JavaScriptSerializer ser  = new JavaScriptSerializer();
                    List <GetSoftware>   lRes = ser.Deserialize <List <GetSoftware> >(response.Result);


                    if (string.IsNullOrEmpty(customerid) && lRes.Count > 400)
                    {
                        try
                        {
                            File.WriteAllText(Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), "rzcat.json"), response.Result);
                        }
                        catch { }
                    }

                    return(lRes);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("E2" + ex.Message, "GetCatalog");
                _sURL = ""; //enforce reload endpoint URL
            }

            return(new List <GetSoftware>());
        }
Esempio n. 34
0
        private void sendButton_Click(object sender, RoutedEventArgs e)
        {
            TcpClient client = new TcpClient();

            try
            {
                //conectar ao servidor no IP local, porta 8001
                client.Connect(GetLocalIPAddress().ToString(), 8001);
                Stream stream = client.GetStream();

                //criar objeto de transacao com os dados informados na tela
                Transaction transaction = new Transaction
                {
                    amount = string.IsNullOrEmpty(amount.Text) ? -1 : Decimal.Parse(amount.Text),
                    type   = type.Text,
                    card   = new Card
                    {
                        cardholderName = cardholderName.Text,
                        number         = cardNumber.Text,
                        expirationDate = expirationDate.Text,
                        cardBrand      = cardBrand.Text,
                        password       = password.Password,
                        type           = cardType.Text,
                        hasPassword    = (bool)hasPassword.IsChecked
                    },
                    number = number.SelectedIndex + 1
                };

                //criar objeto de requisicao
                Request request = new Request {
                    url        = "/transaction",
                    dataObject = transaction
                };

                //transformar objeto em json
                var json = new JavaScriptSerializer().Serialize(request);

                //transmitir json ao servidor
                byte[] sentBytes = Encoding.UTF8.GetBytes(json);
                stream.Write(sentBytes, 0, sentBytes.Length);

                //receber retorno do servidor
                byte[] receivedBytes = new byte[100];
                int    k             = stream.Read(receivedBytes, 0, 100);
                Array.Resize(ref receivedBytes, k);

                //transformar json em objeto
                json = Encoding.UTF8.GetString(receivedBytes);
                Return returnObj = new JavaScriptSerializer().Deserialize <Return>(json);

                //exibir o retorno do servidor
                MessageBox.Show(returnObj.message);
            }

            catch (Exception ex)
            {
                MessageBox.Show("Erro: " + ex.Message);
            }

            finally
            {
                client.Close();
            }
        }
Esempio n. 35
0
        public String GetCurrentStock()
        {
            // Fake response - this would be replaced with a request that is serialized into an object
            StockApiResponse objResponse = new StockApiResponse()
            {
                RequestId = Guid.NewGuid().ToString(),
                TimeStamp = DateTime.Now,

                Stock = new List <StockItem> {
                    new StockItem {
                        Name        = "Product 1",
                        Description = "Placeholder description..",
                        ImageSrc    = "../images/shoe.jpeg",
                        ExternalURL = "https://google.co.uk"
                    },
                    new StockItem {
                        Name        = "Product 2",
                        Description = "Placeholder description..",
                        ImageSrc    = "../images/shoe.jpeg",
                        ExternalURL = "https://google.co.uk"
                    },
                    new StockItem {
                        Name        = "Product 3",
                        Description = "Placeholder description..",
                        ImageSrc    = "../images/shoe.jpeg",
                        ExternalURL = "https://google.co.uk"
                    },
                    new StockItem {
                        Name        = "Product 4",
                        Description = "Placeholder description..",
                        ImageSrc    = "../images/shoe.jpeg",
                        ExternalURL = "https://google.co.uk"
                    },
                    new StockItem {
                        Name        = "Product 5",
                        Description = "Placeholder description..",
                        ImageSrc    = "../images/shoe.jpeg",
                        ExternalURL = "https://google.co.uk"
                    },
                    new StockItem {
                        Name        = "Product 6",
                        Description = "Placeholder description..",
                        ImageSrc    = "../images/shoe.jpeg",
                        ExternalURL = "https://google.co.uk"
                    },
                    new StockItem {
                        Name        = "Product 7",
                        Description = "Placeholder description..",
                        ImageSrc    = "../images/shoe.jpeg",
                        ExternalURL = "https://google.co.uk"
                    },
                    new StockItem {
                        Name        = "Product 8",
                        Description = "Placeholder description..",
                        ImageSrc    = "../images/shoe.jpeg",
                        ExternalURL = "https://google.co.uk"
                    },
                    new StockItem {
                        Name        = "Product 9",
                        Description = "Placeholder description..",
                        ImageSrc    = "../images/shoe.jpeg",
                        ExternalURL = "https://google.co.uk"
                    },
                    new StockItem {
                        Name        = "Product 10",
                        Description = "Placeholder description..",
                        ImageSrc    = "../images/shoe.jpeg",
                        ExternalURL = "https://google.co.uk"
                    },
                }
            };

            // Serialize & return object
            objSeralizer = new JavaScriptSerializer();
            return(objSeralizer.Serialize(objResponse));
        }
Esempio n. 36
0
        public void GetMatchData(Int64 Match_ID)
        {
            JavaScriptSerializer ser       = new JavaScriptSerializer();
            MatchData            matchdata = new MatchData();
            int        IsAny     = 1;
            string     message   = "";
            PlayerData GuestData = new PlayerData();
            Int64      playerid  = 0;

            try
            {
                // SqlDataReader reader;
                using (SqlConnection connection = new SqlConnection(DBConnection.ConnectionString))
                {
                    connection.Open();

                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandText = "SELECT * FROM match where Match_ID=@Match_ID";
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection  = connection;
                    cmd.Parameters.AddWithValue("@Match_ID", Match_ID);
                    SqlDataAdapter adpt      = new SqlDataAdapter(cmd);
                    DataTable      dataTable = new DataTable();
                    adpt.Fill(dataTable);

                    matchdata.Match_Price      = Convert.ToInt64(dataTable.Rows[0]["Match_Price"]);
                    matchdata.Host_Rem_amount  = Convert.ToInt64(dataTable.Rows[0]["Host_Rem_amount"]);
                    matchdata.Guest_Rem_amount = Convert.ToInt64(dataTable.Rows[0]["Guest_Rem_amount"]);

                    matchdata.Match_Status = Convert.ToInt32(dataTable.Rows[0]["Match_Status"]);
                    matchdata.Match_ID     = Convert.ToInt64(dataTable.Rows[0]["Match_ID"]);
                    matchdata.Host_ID      = Convert.ToInt64(dataTable.Rows[0]["Host_ID"]);
                    matchdata.Guest_ID     = Convert.ToInt64(dataTable.Rows[0]["Guest_ID"]);
                    playerid              = matchdata.Guest_ID;
                    GuestData             = GetPlayertData(playerid);
                    matchdata.Guest_Name  = Convert.ToString(GuestData.PlayerName);
                    matchdata.Guest_Total = Convert.ToInt64(GuestData.PlayerTotal);
                    matchdata.Guest_Stars = Convert.ToInt32(GuestData.PlayerStars);

                    matchdata.Host_Num  = Convert.ToInt32(dataTable.Rows[0]["Host_Num"]);
                    matchdata.Guest_Num = Convert.ToInt32(dataTable.Rows[0]["Guest_Num"]);
                    matchdata.Winner_ID = Convert.ToInt64(dataTable.Rows[0]["Winner_ID"]);



                    // dataTable.Clear();
                    connection.Close();
                }
            }
            catch (Exception ex)
            {
                IsAny   = 0;
                message = ex.Message;
            }
            var jsonData = new
            {
                IsAny            = IsAny,
                message          = message,
                Match_Status     = matchdata.Match_Status,
                Match_ID         = matchdata.Match_ID,
                Match_Price      = matchdata.Match_Price,
                Host_Rem_amount  = matchdata.Host_Rem_amount,
                Guest_Rem_amount = matchdata.Guest_Rem_amount,
                Host_Num         = matchdata.Host_Num,
                Host_ID          = matchdata.Host_ID,
                Guest_ID         = matchdata.Guest_ID,
                Guest_Num        = matchdata.Guest_Num,
                Winner_ID        = matchdata.Winner_ID,
                Guest_Name       = matchdata.Guest_Name,
                Guest_Total      = matchdata.Guest_Total,
                Guest_Stars      = matchdata.Guest_Stars
            };

            HttpContext.Current.Response.Write(ser.Serialize(jsonData));
        }
Esempio n. 37
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="serializer"></param>
 /// <returns></returns>
 protected internal abstract object AsSerializedValue(JavaScriptSerializer serializer);
Esempio n. 38
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="obj"></param>
 /// <param name="serializer"></param>
 protected virtual void OnDeserialize(object obj, JavaScriptSerializer serializer)
 {
 }
Esempio n. 39
0
        public AdminModule(IRootPathProvider pathProvider) : base("admin")
        {
            Get("/login", _ =>
            {
                return(View["admin/login"]);
            });

            Post("/login", _ => {
                var userGuid = UserMapper.ValidateUser((string)this.Request.Form.login, (string)this.Request.Form.password);

                if (userGuid == null)
                {
                    return(this.Context.GetRedirect("~/admin/login?error=true&username="******"/logout", _ => {
                return(this.LogoutAndRedirect("~/admin"));
            });

            Get("/", _ =>
            {
                return(View["admin/index"]);
            });

            Get("/settings", _ =>
            {
                this.RequiresAuthentication();

                using (var db = new LiteDatabase("Meta.db"))
                {
                    var pictureUrlBase = db.GetCollection <KeyValue>("Settings")
                                         .FindById("pictureUrlBase").Value;

                    return(View["admin/settings", pictureUrlBase]);
                }
            });

            Post("/settings", _ =>
            {
                this.RequiresAuthentication();

                var newHostUrl = (string)this.Request.Form.hostUrl;

                if (!string.IsNullOrEmpty(newHostUrl))
                {
                    using (var db = new LiteDatabase(@"Meta.db"))
                    {
                        db.GetCollection <KeyValue>("Settings")
                        .Update("pictureUrlBase",
                                new KeyValue()
                        {
                            Key   = "pictureUrlBase",
                            Value = newHostUrl
                        }
                                );
                    }
                }

                var newPassword = (string)this.Request.Form.password;

                if (!string.IsNullOrEmpty(newPassword))
                {
                    var sha512 = SHA512.Create();
                    var hash   = sha512.ComputeHash(Encoding.UTF8.GetBytes(newPassword));
                    using (var db = new LiteDatabase(@"Meta.db"))
                    {
                        db.GetCollection <KeyValue>("Settings")
                        .Update("password",
                                new KeyValue()
                        {
                            Key   = "password",
                            Value = UserMapper.ByteArrayToString(hash)
                        }
                                );
                    }
                }

                return(this.Context.GetRedirect("~/admin"));
            });

            Get("/view-class-meta", _ =>
            {
                this.RequiresAuthentication();

                using (var db = new LiteDatabase(@"Meta.db"))
                {
                    var meta     = db.GetCollection <Meta>("ClassMeta").FindAll().ToList();
                    var viewMeta = meta.Select(metai =>
                                               new
                    {
                        MetaId            = metai.MetaId,
                        Name              = metai.Name,
                        Description       = metai.Description,
                        PictureUrl        = metai.PictureUrl,
                        PreviewPictureUrl = metai.PreviewPictureUrl,
                        Tags              = JsonConvert.SerializeObject(metai.Tags)
                    }
                                               );
                    return(View["admin/view-class-meta", viewMeta]);
                }
            });

            Get("/add-class-meta", _ =>
            {
                this.RequiresAuthentication();

                return(View["admin/add-class-meta"]);
            });

            Post("/add-class-meta", async(ctx, ct) =>
            {
                this.RequiresAuthentication();

                var metaId = (string)this.Request.Form.metaId;
                var name   = (string)this.Request.Form.name;
                var desc   = (string)this.Request.Form.description;
                var tags   = (string)this.Request.Form.tags;

                if (string.IsNullOrEmpty(desc))
                {
                    desc = "";
                }
                if (string.IsNullOrEmpty(tags))
                {
                    tags = "{}";
                }

                Dictionary <string, List <string> > tagsDecoded = JsonConvert.DeserializeObject <Dictionary <string, List <string> > >(tags);

                var imageUrl = this.Request.Url.BasePath +
                               await HandleUploadAsync(
                    pathProvider,
                    metaId,
                    this.Request.Files.First(file => file.Key == "image").Name.Substring(
                        this.Request.Files.First(file => file.Key == "image").Name.LastIndexOf('.')
                        ),
                    this.Request.Files.First(file => file.Key == "image").Value,
                    false,
                    false
                    );
                var previewImageUrl = this.Request.Url.BasePath +
                                      await HandleUploadAsync(
                    pathProvider,
                    metaId,
                    this.Request.Files.First(file => file.Key == "previewImage").Name.Substring(
                        this.Request.Files.First(file => file.Key == "previewImage").Name.LastIndexOf('.')
                        ),
                    this.Request.Files.First(file => file.Key == "previewImage").Value,
                    false,
                    true
                    );
                using (var db = new LiteDatabase(@"Meta.db"))
                {
                    db.GetCollection <Meta>("ClassMeta").Insert(
                        new Meta()
                    {
                        MetaId            = metaId,
                        Name              = name,
                        Description       = desc,
                        PictureUrl        = imageUrl,
                        PreviewPictureUrl = previewImageUrl,
                        Tags              = tagsDecoded
                    }
                        );
                }
                return(this.Context.GetRedirect("~/admin/view-class-meta"));
            });

            Post("/delete-class-meta", _ =>
            {
                this.RequiresAuthentication();

                var metaId = (string)this.Request.Form.metaId;

                using (var db = new LiteDatabase(@"Meta.db"))
                {
                    var meta = db.GetCollection <Meta>("ClassMeta").FindById(metaId);

                    if (!string.IsNullOrEmpty(meta.PictureUrl) && File.Exists(meta.PictureUrl))
                    {
                        File.Delete(meta.PictureUrl);
                    }
                    if (!string.IsNullOrEmpty(meta.PreviewPictureUrl) && File.Exists(meta.PreviewPictureUrl))
                    {
                        File.Delete(meta.PreviewPictureUrl);
                    }
                    db.GetCollection <Meta>("ClassMeta").Delete(metaId);
                }
                return(this.Context.GetRedirect("~/admin/view-class-meta"));
            });

            Get("/view-instance-meta", _ =>
            {
                this.RequiresAuthentication();

                using (var db = new LiteDatabase(@"Meta.db"))
                {
                    var meta     = db.GetCollection <Meta>("InstanceMeta").FindAll().ToList();
                    var viewMeta = meta.Select(metai =>
                                               new
                    {
                        MetaId            = metai.MetaId,
                        Name              = metai.Name,
                        Description       = metai.Description,
                        PictureUrl        = metai.PictureUrl,
                        PreviewPictureUrl = metai.PreviewPictureUrl,
                        Tags              = JsonConvert.SerializeObject(metai.Tags)
                    }
                                               );
                    return(View["admin/view-instance-meta", viewMeta]);
                }
            });

            Get("/add-instance-meta", _ =>
            {
                this.RequiresAuthentication();

                return(View["admin/add-instance-meta"]);
            });

            Post("/add-instance-meta", async(ctx, ct) =>
            {
                this.RequiresAuthentication();

                var metaId = (string)this.Request.Form.metaId;
                var name   = (string)this.Request.Form.name;
                var desc   = (string)this.Request.Form.description;
                var tags   = (string)this.Request.Form.tags;

                if (string.IsNullOrEmpty(tags))
                {
                    tags = "{}";
                }

                var tagsDecoded = new JavaScriptSerializer().Deserialize <Dictionary <string, List <string> > >(tags);

                bool hasImage = this.Request.Files.Any(file => file.Key == "image");

                string imageUrl = "";

                if (hasImage)
                {
                    imageUrl = this.Request.Url.BasePath +
                               await HandleUploadAsync(
                        pathProvider,
                        metaId,
                        this.Request.Files.First(file => file.Key == "image").Name.Substring(
                            this.Request.Files.First(file => file.Key == "image").Name.LastIndexOf('.')
                            ),
                        this.Request.Files.First(file => file.Key == "image").Value,
                        true,
                        false
                        );
                }

                bool hasPreviewImage = this.Request.Files.Any(file => file.Key == "previewImage");

                string previewImageUrl = "";

                if (hasPreviewImage)
                {
                    previewImageUrl = this.Request.Url.BasePath +
                                      await HandleUploadAsync(
                        pathProvider,
                        metaId,
                        this.Request.Files.First(file => file.Key == "previewImage").Name.Substring(
                            this.Request.Files.First(file => file.Key == "previewImage").Name.LastIndexOf('.')
                            ),
                        this.Request.Files.First(file => file.Key == "previewImage").Value,
                        true,
                        true
                        );
                }

                using (var db = new LiteDatabase(@"Meta.db"))
                {
                    db.GetCollection <Meta>("InstanceMeta").Insert(
                        new Meta()
                    {
                        MetaId            = metaId,
                        Name              = string.IsNullOrEmpty(name) ? null : name,
                        Description       = string.IsNullOrEmpty(desc) ? null : desc,
                        PictureUrl        = string.IsNullOrEmpty(imageUrl) ? null : imageUrl,
                        PreviewPictureUrl = string.IsNullOrEmpty(previewImageUrl) ? null : previewImageUrl,
                        Tags              = tagsDecoded
                    }
                        );
                }
                return(this.Context.GetRedirect("~/admin/view-instance-meta"));
            });

            Post("/delete-instance-meta", _ =>
            {
                this.RequiresAuthentication();

                var metaId = (string)this.Request.Form.metaId;

                using (var db = new LiteDatabase(@"Meta.db"))
                {
                    var meta = db.GetCollection <Meta>("InstanceMeta").FindById(metaId);

                    if (!string.IsNullOrEmpty(meta.PictureUrl) && File.Exists(meta.PictureUrl))
                    {
                        File.Delete(meta.PictureUrl);
                    }
                    if (!string.IsNullOrEmpty(meta.PreviewPictureUrl) && File.Exists(meta.PreviewPictureUrl))
                    {
                        File.Delete(meta.PreviewPictureUrl);
                    }
                    db.GetCollection <Meta>("InstanceMeta").Delete(metaId);
                }
                return(this.Context.GetRedirect("~/admin/view-instance-meta"));
            });
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        Conn.Open();

        userID  = Session["userID"].ToString();
        bookID  = Request.Form["bookID"];
        grade   = Request.Form["grade"];
        content = Request.Form["content"];

        // 查書籍借閱者ID
        String borrowerIDsql = "SELECT [Lease].BorrowerID " +
                               "FROM [Lease] " +
                               "WHERE [Lease].LeaseID='" + bookID + "'";
        SqlCommand    borrowerIDCmd = new SqlCommand(borrowerIDsql, Conn);
        SqlDataReader borrowerIDdr  = borrowerIDCmd.ExecuteReader();

        while (borrowerIDdr.Read())
        {
            borrowerID = borrowerIDdr["BorrowerID"].ToString();
        }

        borrowerIDCmd.Cancel();
        borrowerIDdr.Close();


        // insert letter to 借閱者([Letter].Recipient=borrowerID, [Letter].LeaseID=bookID)
        // findmaxLetterIDsql start
        String findmaxLetterIDsql = "SELECT MAX (CONVERT(int, \"LetterID\")) as maxID " +
                                    "FROM Letter";

        SqlCommand    findmaxLetterIDCmd = new SqlCommand(findmaxLetterIDsql, Conn);
        SqlDataReader findmaxLetterIDdr  = findmaxLetterIDCmd.ExecuteReader();

        while (findmaxLetterIDdr.Read())
        {
            Int16 maxID = Convert.ToInt16(findmaxLetterIDdr["maxID"].ToString());
            nextLetterID = (maxID + 1).ToString();
        }

        findmaxLetterIDCmd.Cancel();
        findmaxLetterIDdr.Close();
        // findmaxLetterIDsql end

        String insertLettersql = "INSERT INTO Letter " +
                                 "VALUES('" + nextLetterID + "', '出租者確認收到書籍', '您已完成租借教材程序','" + borrowerID + "', '0', '" + bookID + "')";
        SqlCommand    insertLetterCmd = new SqlCommand(insertLettersql, Conn);
        SqlDataReader insertLetterdr  = insertLetterCmd.ExecuteReader();

        insertLetterCmd.Cancel();
        insertLetterdr.Close();


        // 更改[lease].RevertSitutaion=2
        String updateLeasesql = "UPDATE [Lease] " +
                                "SET [Lease].RevertSituation='2' " +
                                "WHERE [Lease].LeaseID='" + bookID + "'";
        SqlCommand    updateLeaseCmd = new SqlCommand(updateLeasesql, Conn);
        SqlDataReader updateLeasedr  = updateLeaseCmd.ExecuteReader();

        updateLeaseCmd.Cancel();
        updateLeasedr.Close();

        // 新增UserEvalution
        // findmaxUEvaIDsql start
        String findmaxUEvaIDsql = "SELECT MAX (CONVERT(int, \"UserEvaluationID\")) as maxID " +
                                  "FROM UserEvaluation";

        SqlCommand    findmaxUEvaIDCmd = new SqlCommand(findmaxUEvaIDsql, Conn);
        SqlDataReader findmaxUEvaIDdr  = findmaxUEvaIDCmd.ExecuteReader();

        while (findmaxUEvaIDdr.Read())
        {
            Int16 maxID = Convert.ToInt16(findmaxUEvaIDdr["maxID"].ToString());
            nextUEvaID = (maxID + 1).ToString();
        }

        findmaxUEvaIDCmd.Cancel();
        findmaxUEvaIDdr.Close();
        // findmaxUEvaIDsql end

        // insertEvasql start
        String insertEvasql = "INSERT INTO UserEvaluation " +
                              "VALUES('" + nextUEvaID + "','" + grade + "','" + content + "','" + borrowerID + "', '" + nextLetterID + "')";
        SqlCommand    insertEvaCmd = new SqlCommand(insertEvasql, Conn);
        SqlDataReader insertEvadr  = insertEvaCmd.ExecuteReader();

        insertEvaCmd.Cancel();
        insertEvadr.Close();
        // insertEvasql end

        // ajax back
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        var           responseEntities  = new List <CompleteState>();
        CompleteState state             = new CompleteState {
            state = "success"
        };

        responseEntities.Add(state);

        var result = serializer.Serialize(responseEntities);

        Response.Write(result);
        Response.End();


        Conn.Close();
    }
Esempio n. 41
0
        public static object ConvertFromJson(string input, out ErrorRecord error)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            error = null;
#if CORECLR
            object obj = null;
            try
            {
                // JsonConvert.DeserializeObject does not throw an exception when an invalid Json array is passed.
                // This issue is being tracked by https://github.com/JamesNK/Newtonsoft.Json/issues/1321.
                // To work around this, we need to identify when input is a Json array, and then try to parse it via JArray.Parse().

                // If input starts with '[' (ignoring white spaces).
                if ((Regex.Match(input, @"^\s*\[")).Success)
                {
                    // JArray.Parse() will throw a JsonException if the array is invalid.
                    // This will be caught by the catch block below, and then throw an
                    // ArgumentException - this is done to have same behavior as the JavaScriptSerializer.
                    JArray.Parse(input);

                    // Please note that if the Json array is valid, we don't do anything,
                    // we just continue the deserialization.
                }

                obj = JsonConvert.DeserializeObject(input, new JsonSerializerSettings()
                {
                    TypeNameHandling = TypeNameHandling.None, MaxDepth = 1024
                });

                // JObject is a IDictionary
                var dictionary = obj as JObject;
                if (dictionary != null)
                {
                    obj = PopulateFromJDictionary(dictionary, out error);
                }
                else
                {
                    // JArray is a collection
                    var list = obj as JArray;
                    if (list != null)
                    {
                        obj = PopulateFromJArray(list, out error);
                    }
                }
            }
            catch (JsonException je)
            {
                var msg = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.JsonDeserializationFailed, je.Message);
                // the same as JavaScriptSerializer does
                throw new ArgumentException(msg, je);
            }
#else
            //In ConvertTo-Json, to serialize an object with a given depth, we set the RecursionLimit to depth + 2, see JavaScriptSerializer constructor in ConvertToJsonCommand.cs.
            // Setting RecursionLimit to depth + 2 in order to support '$object | ConvertTo-Json –depth <value less than or equal to 100> | ConvertFrom-Json'.
            JavaScriptSerializer serializer = new JavaScriptSerializer(new JsonObjectTypeResolver())
            {
                RecursionLimit = (maxDepthAllowed + 2)
            };
            serializer.MaxJsonLength = Int32.MaxValue;
            object obj = serializer.DeserializeObject(input);

            if (obj is IDictionary <string, object> )
            {
                var dictionary = obj as IDictionary <string, object>;
                obj = PopulateFromDictionary(dictionary, out error);
            }
            else if (obj is ICollection <object> )
            {
                var list = obj as ICollection <object>;
                obj = PopulateFromList(list, out error);
            }
#endif
            return(obj);
        }
Esempio n. 42
0
        public ActionResult RenderSubAreaList(string subAreaList, string selectSubAreaList, int?deleteId, int?subAreaId, string subAreaName, string status, string updateUser, string updateDate)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("Render SubArea").ToInputLogString());

            if (!string.IsNullOrEmpty(status))
            {
                if (status.ToLower() == "true")
                {
                    status = "Active";
                }
                else if (status.ToLower() == "false")
                {
                    status = "Inactive";
                }
            }

            try
            {
                if (ModelState.IsValid)
                {
                    var subAreaTableModel = new SubAreaViewModel();
                    var areaList          = new JavaScriptSerializer().Deserialize <SubAreaTableModel[]>(subAreaList);
                    subAreaTableModel.SubAreaTableList = new List <SubAreaTableModel>();

                    foreach (var item in areaList)
                    {
                        if (!deleteId.HasValue || item.id != deleteId.Value)
                        {
                            var model = new SubAreaTableModel()
                            {
                                id          = item.id,
                                area_name   = item.area_name,
                                status      = item.status,
                                update_name = item.update_name,
                                update_date = item.update_date
                            };

                            subAreaTableModel.SubAreaTableList.Add(model);
                        }
                    }

                    if (selectSubAreaList != "null")
                    {
                        var selectSubList = new JavaScriptSerializer().Deserialize <SubAreaTableModel[]>(selectSubAreaList);
                        foreach (var item in selectSubList)
                        {
                            if (!deleteId.HasValue || item.id != deleteId.Value)
                            {
                                var model = new SubAreaTableModel()
                                {
                                    id          = item.id,
                                    area_name   = item.area_name,
                                    status      = item.status,
                                    update_name = item.update_name,
                                    update_date = item.update_date
                                };

                                subAreaTableModel.SubAreaTableList.Add(model);
                            }
                        }
                    }

                    if (subAreaId.HasValue)
                    {
                        var model = new SubAreaTableModel()
                        {
                            id          = subAreaId.Value,
                            area_name   = subAreaName,
                            status      = status,
                            update_name = updateUser,
                            update_date = updateDate
                        };

                        subAreaTableModel.SubAreaTableList.Add(model);
                    }

                    subAreaTableModel.SubAreaTableList = subAreaTableModel.SubAreaTableList.OrderBy(q => q.area_name).ToList();
                    return(PartialView("~/Views/Area/_RenderSubAreaList.cshtml", subAreaTableModel));
                }

                return(Json(new
                {
                    Valid = false,
                    Error = string.Empty
                }));
            }
            catch (Exception ex)
            {
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Render SubArea").ToFailLogString());
                return(Error(new HandleErrorInfo(ex, this.ControllerContext.RouteData.Values["controller"].ToString(),
                                                 this.ControllerContext.RouteData.Values["action"].ToString())));
            }
        }
Esempio n. 43
0
        static void Main(string[] args)
        {
            bool     statu;
            string   date1, date2;
            DateTime addDay;
            //change this connection
            SqlConnection conn  = new SqlConnection("Data Source=[adress];Initial Catalog=[database];Integrated Security=False;User ID=sa;Password=[saPass];Connect Timeout=15;Encrypt=False;Packet Size=4096");
            DateTime      today = DateTime.Now;

            addDay = today.AddDays(1);
            date1  = today.ToString("ddMMyyyy");
            date2  = addDay.ToString("ddMMyyyy");
            try
            {
                Console.WriteLine("Reading data...");
                //change this url
                string Url = string.Format(@"http://site.com/?username=&password=&action=cdr&date1={0}0000&date2={1}0000", date1, date2);

                var json = new WebClient().DownloadString(Url);
                Thread.Sleep(1000);
                var serializer = new JavaScriptSerializer();
                var resultObj  = serializer.Deserialize <List <Json> >(json);
                Console.WriteLine("Database connection...");
                Thread.Sleep(1000);
                Console.WriteLine("Json data converting for sql server...");
                //change the model
                foreach (var item in resultObj[0].data)
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        repeated(item.id);
                        if (statu == true)
                        {
                            cmd.Connection = conn;
                            conn.Open();
                            //change this command and parameters
                            cmd.CommandText = "Insert into [DbName] (callno,calldate,calltype,src,dst,duration,disposition,queue,record) values (@callno,@calldate,@calltype,@src,@dst,@duration,@disposition,@queue,@record)";
                            cmd.Parameters.AddWithValue("@callno", item.id);
                            cmd.Parameters.AddWithValue("@calldate", item.calldate);
                            cmd.Parameters.AddWithValue("@calltype", item.calltype);
                            cmd.Parameters.AddWithValue("@src", item.src);
                            cmd.Parameters.AddWithValue("@dst", item.dst);
                            cmd.Parameters.AddWithValue("@duration", item.duration);
                            cmd.Parameters.AddWithValue("@disposition", item.disposition);
                            cmd.Parameters.AddWithValue("@queue", item.queue);
                            cmd.Parameters.AddWithValue("@record", item.record);
                            cmd.ExecuteNonQuery();
                            conn.Close();
                        }
                    }
                }
                Console.WriteLine("Database jobs is finished. Exiting now...");
                Thread.Sleep(2000);
            }

            catch (Exception ex)
            {
                Console.WriteLine("Fail.");
            }
            void repeated(string callno)
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("select Id,callno from SesKayitVerileri where callno=@p1", conn);

                cmd.Parameters.AddWithValue("@p1", callno);
                SqlDataReader dr = cmd.ExecuteReader();

                if (dr.Read())
                {
                    statu = false;
                }
                else
                {
                    statu = true;
                }
                conn.Close();
            }
        }
Esempio n. 44
0
 /// <summary>
 /// USE JavaScriptSerializer
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 public static string ToJson(object obj)
 {
     var serializer = new JavaScriptSerializer();
     
     return serializer.Serialize(obj);
 }
        static void Main(string[] args)
        {
            var json = @"{
         ""authenticated"": true,
         ""user"": ""sathyabhat"",
         ""feeds"": {
             ""96705"": {
                 ""feed_address"": ""http://www.linuxhaxor.net/"",
                 ""updated"": ""8492 hours"",
                 ""favicon_text_color"": null,
                 ""subs"": 35,
                 ""feed_link"": ""http://www.linuxhaxor.net/"",
                 ""favicon_fetching"": true,
                 ""nt"": 0,
                 ""updated_seconds_ago"": 30573336,
                 ""num_subscribers"": 35,
                 ""feed_title"": ""LinuxHaxor.net"",
                 ""favicon_fade"": null,
                 ""exception_type"": ""feed"",
                 ""exception_code"": 503,
                 ""favicon_color"": null,
                 ""active"": true,
                 ""ng"": 0,
                 ""feed_opens"": 0,
                 ""id"": 96705,
                 ""ps"": 0,
                 ""has_exception"": true
             },
             ""768840"": {
                 ""feed_address"": ""http://feeds.feedburner.com/PathikShahDotCom"",
                 ""updated"": ""3 hours"",
                 ""favicon_text_color"": ""black"",
                 ""subs"": 1,
                 ""feed_link"": ""http://www.pathikshah.com/blog"",
                 ""favicon_fetching"": false,
                 ""nt"": 0,
                 ""updated_seconds_ago"": 13043,
                 ""num_subscribers"": 1,
                 ""feed_title"": ""Pathik Shah"",
                 ""favicon_fade"": ""769456"",
                 ""favicon_color"": ""b2d092"",
                 ""active"": true,
                 ""ng"": 0,
                 ""feed_opens"": 0,
                 ""id"": 768840,
                 ""ps"": 0
             },
             ""768842"": {
                 ""feed_address"": ""http://feeds.preshit.net/preshit/blog"",
                 ""updated"": ""3 hours"",
                 ""favicon_text_color"": null,
                 ""subs"": 1,
                 ""feed_link"": ""http://preshit.net"",
                 ""favicon_fetching"": false,
                 ""nt"": 3,
                 ""updated_seconds_ago"": 13536,
                 ""num_subscribers"": 1,
                 ""feed_title"": ""Preshit Deorukhkar"",
                 ""favicon_fade"": null,
                 ""favicon_color"": null,
                 ""active"": true,
                 ""ng"": 0,
                 ""feed_opens"": 1,
                 ""id"": 768842,
                 ""ps"": 0
             },
             ""768843"": {
                 ""feed_address"": ""http://quizwith.net/feed/"",
                 ""updated"": ""3 hours"",
                 ""favicon_text_color"": ""white"",
                 ""subs"": 1,
                 ""feed_link"": ""http://quizwith.net"",
                 ""favicon_fetching"": false,
                 ""nt"": 0,
                 ""updated_seconds_ago"": 11617,
                 ""num_subscribers"": 1,
                 ""feed_title"": ""quizwith.net"",
                 ""favicon_fade"": ""c22900"",
                 ""favicon_color"": ""fe6501"",
                 ""active"": true,
                 ""ng"": 0,
                 ""feed_opens"": 0,
                 ""id"": 768843,
                 ""ps"": 0
             }
         },
         ""flat_folders"": { },
         result: ""ok"" }";

            var jsonSerializer = new JavaScriptSerializer();
            var response       = jsonSerializer.Deserialize < FeedResponse(json);

            Console.Write(jsonSerializer.Serialize(response));
            Console.ReadKey();
        }
Esempio n. 46
0
        private UploadResponse UploadFile(string b64hash, string type, long size, string path, string to, string contenttype)
        {
            ProtocolTreeNode media = new ProtocolTreeNode("media", new KeyValue[] {
                new KeyValue("xmlns", "w:m"),
                new KeyValue("hash", b64hash),
                new KeyValue("type", type),
                new KeyValue("size", size.ToString())
            });
            string           id   = TicketManager.GenerateId();
            ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] {
                new KeyValue("id", id),
                new KeyValue("to", WhatsConstants.WhatsAppServer),
                new KeyValue("type", "set")
            }, media);

            this.uploadResponse = null;
            this.WhatsSendHandler.SendNode(node);
            int i = 0;

            while (this.uploadResponse == null && i < 5)
            {
                i++;
                this.PollMessages();
            }
            if (this.uploadResponse != null && this.uploadResponse.GetChild("duplicate") != null)
            {
                UploadResponse res = new UploadResponse(this.uploadResponse);
                this.uploadResponse = null;
                return(res);
            }
            else
            {
                try
                {
                    string uploadUrl = this.uploadResponse.GetChild("media").GetAttribute("url");
                    this.uploadResponse = null;

                    Uri uri = new Uri(uploadUrl);

                    string        hashname = string.Empty;
                    byte[]        buff     = MD5.Create().ComputeHash(System.Text.Encoding.Default.GetBytes(path));
                    StringBuilder sb       = new StringBuilder();
                    foreach (byte b in buff)
                    {
                        sb.Append(b.ToString("X2"));
                    }
                    hashname = String.Format("{0}.{1}", sb.ToString(), path.Split('.').Last());

                    string boundary = "zzXXzzYYzzXXzzQQ";

                    sb = new StringBuilder();

                    sb.AppendFormat("--{0}\r\n", boundary);
                    sb.Append("Content-Disposition: form-data; name=\"to\"\r\n\r\n");
                    sb.AppendFormat("{0}\r\n", to);
                    sb.AppendFormat("--{0}\r\n", boundary);
                    sb.Append("Content-Disposition: form-data; name=\"from\"\r\n\r\n");
                    sb.AppendFormat("{0}\r\n", this.phoneNumber);
                    sb.AppendFormat("--{0}\r\n", boundary);
                    sb.AppendFormat("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\n", hashname);
                    sb.AppendFormat("Content-Type: {0}\r\n\r\n", contenttype);
                    string header = sb.ToString();

                    sb = new StringBuilder();
                    sb.AppendFormat("\r\n--{0}--\r\n", boundary);
                    string footer = sb.ToString();

                    long clength = size + header.Length + footer.Length;

                    sb = new StringBuilder();
                    sb.AppendFormat("POST {0}\r\n", uploadUrl);
                    sb.AppendFormat("Content-Type: multipart/form-data; boundary={0}\r\n", boundary);
                    sb.AppendFormat("Host: {0}\r\n", uri.Host);
                    sb.AppendFormat("User-Agent: {0}\r\n", WhatsConstants.UserAgent);
                    sb.AppendFormat("Content-Length: {0}\r\n\r\n", clength);
                    string post = sb.ToString();

                    TcpClient tc  = new TcpClient(uri.Host, 443);
                    SslStream ssl = new SslStream(tc.GetStream());
                    try
                    {
                        ssl.AuthenticateAsClient(uri.Host);
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }

                    List <byte> buf = new List <byte>();
                    buf.AddRange(Encoding.UTF8.GetBytes(post));
                    buf.AddRange(Encoding.UTF8.GetBytes(header));
                    buf.AddRange(File.ReadAllBytes(path));
                    buf.AddRange(Encoding.UTF8.GetBytes(footer));

                    ssl.Write(buf.ToArray(), 0, buf.ToArray().Length);

                    //moment of truth...
                    buff = new byte[1024];
                    ssl.Read(buff, 0, 1024);

                    string result = Encoding.UTF8.GetString(buff);
                    foreach (string line in result.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (line.StartsWith("{"))
                        {
                            string fooo = line.TrimEnd(new char[] { (char)0 });
                            JavaScriptSerializer jss  = new JavaScriptSerializer();
                            UploadResponse       resp = jss.Deserialize <UploadResponse>(fooo);
                            if (!String.IsNullOrEmpty(resp.url))
                            {
                                return(resp);
                            }
                        }
                    }
                }
                catch (Exception)
                { }
            }
            return(null);
        }
Esempio n. 47
0
        Task StartWriter(BlockingCollection <LocalAdminInfo> output, TaskFactory factory)
        {
            return(factory.StartNew(() =>
            {
                if (options.URI == null)
                {
                    string path = options.GetFilePath("local_admins");
                    bool append = false || File.Exists(path);
                    using (StreamWriter writer = new StreamWriter(path, append))
                    {
                        if (!append)
                        {
                            writer.WriteLine("ComputerName,AccountName,AccountType");
                        }
                        int localcount = 0;
                        foreach (LocalAdminInfo info in output.GetConsumingEnumerable())
                        {
                            writer.WriteLine(info.ToCSV());
                            localcount++;
                            if (localcount % 100 == 0)
                            {
                                writer.Flush();
                            }
                        }
                        writer.Flush();
                    }
                }
                else
                {
                    using (WebClient client = new WebClient())
                    {
                        client.Headers.Add("content-type", "application/json");
                        client.Headers.Add("Accept", "application/json; charset=UTF-8");
                        client.Headers.Add("Authorization", options.GetEncodedUserPass());

                        int localcount = 0;

                        RESTOutput groups = new RESTOutput(Query.LocalAdminGroup);
                        RESTOutput computers = new RESTOutput(Query.LocalAdminComputer);
                        RESTOutput users = new RESTOutput(Query.LocalAdminUser);

                        JavaScriptSerializer serializer = new JavaScriptSerializer();

                        foreach (LocalAdminInfo info in output.GetConsumingEnumerable())
                        {
                            switch (info.ObjectType)
                            {
                            case "user":
                                users.props.Add(info.ToParam());
                                break;

                            case "group":
                                groups.props.Add(info.ToParam());
                                break;

                            case "computer":
                                computers.props.Add(info.ToParam());
                                break;
                            }
                            localcount++;
                            if (localcount % 1000 == 0)
                            {
                                var ToPost = serializer.Serialize(new
                                {
                                    statements = new object[] {
                                        users.GetStatement(),
                                        computers.GetStatement(),
                                        groups.GetStatement()
                                    }
                                });

                                users.Reset();
                                computers.Reset();
                                groups.Reset();

                                try
                                {
                                    client.UploadData("http://localhost:7474/db/data/transaction/commit", "POST", Encoding.Default.GetBytes(ToPost));
                                }catch (Exception e)
                                {
                                    Console.WriteLine(e);
                                }
                            }
                        }

                        var FinalPost = serializer.Serialize(new
                        {
                            statements = new object[] {
                                users.GetStatement(),
                                computers.GetStatement(),
                                groups.GetStatement()
                            }
                        });

                        try
                        {
                            client.UploadData("http://localhost:7474/db/data/transaction/commit", "POST", Encoding.Default.GetBytes(FinalPost));
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }
                }
            }));
        }
Esempio n. 48
0
        public JsonResult WriteScriptSettings(CustomElements Detalle_de_Descripcion_de_Evidencia_CCModuleAttributeList)
        {
            for (int i = 0; i < Detalle_de_Descripcion_de_Evidencia_CCModuleAttributeList.CustomModuleAttributeList.Count - 1; i++)
            {
                if (string.IsNullOrEmpty(Detalle_de_Descripcion_de_Evidencia_CCModuleAttributeList.CustomModuleAttributeList[i].DefaultValue))
                {
                    Detalle_de_Descripcion_de_Evidencia_CCModuleAttributeList.CustomModuleAttributeList[i].DefaultValue = string.Empty;
                }
                if (string.IsNullOrEmpty(Detalle_de_Descripcion_de_Evidencia_CCModuleAttributeList.CustomModuleAttributeList[i].HelpText))
                {
                    Detalle_de_Descripcion_de_Evidencia_CCModuleAttributeList.CustomModuleAttributeList[i].HelpText = string.Empty;
                }
            }
            if (Detalle_de_Descripcion_de_Evidencia_CCModuleAttributeList.ChildModuleAttributeList != null)
            {
                for (int i = 0; i < Detalle_de_Descripcion_de_Evidencia_CCModuleAttributeList.ChildModuleAttributeList.Count - 1; i++)
                {
                    if (string.IsNullOrEmpty(Detalle_de_Descripcion_de_Evidencia_CCModuleAttributeList.ChildModuleAttributeList[i].DefaultValue))
                    {
                        Detalle_de_Descripcion_de_Evidencia_CCModuleAttributeList.ChildModuleAttributeList[i].DefaultValue = string.Empty;
                    }
                    if (string.IsNullOrEmpty(Detalle_de_Descripcion_de_Evidencia_CCModuleAttributeList.ChildModuleAttributeList[i].HelpText))
                    {
                        Detalle_de_Descripcion_de_Evidencia_CCModuleAttributeList.ChildModuleAttributeList[i].HelpText = string.Empty;
                    }
                }
            }
            string strDetalle_de_Descripcion_de_Evidencia_CCScript = string.Empty;

            using (StreamReader r = new StreamReader(Server.MapPath("~/Uploads/Scripts/Detalle_de_Descripcion_de_Evidencia_CC.js")))
            {
                strDetalle_de_Descripcion_de_Evidencia_CCScript = r.ReadToEnd();
            }

            JavaScriptSerializer jsSerialize = new JavaScriptSerializer();

            // get json string of change Detalle_de_Descripcion_de_Evidencia_CC element attributes
            string userChangeJson = jsSerialize.Serialize(Detalle_de_Descripcion_de_Evidencia_CCModuleAttributeList.CustomModuleAttributeList);

            int    indexOfArray          = strDetalle_de_Descripcion_de_Evidencia_CCScript.IndexOf("inpuElementArray");
            string splittedString        = strDetalle_de_Descripcion_de_Evidencia_CCScript.Substring(indexOfArray, strDetalle_de_Descripcion_de_Evidencia_CCScript.Length - indexOfArray);
            int    indexOfMainElement    = splittedString.IndexOf('[');
            int    endIndexOfMainElement = splittedString.IndexOf(']') + 1;

            // get json string of change job history element attributes
            string childUserChangeJson          = jsSerialize.Serialize(Detalle_de_Descripcion_de_Evidencia_CCModuleAttributeList.ChildModuleAttributeList);
            int    indexOfArrayHistory          = 0;
            string splittedStringHistory        = "";
            int    indexOfMainElementHistory    = 0;
            int    endIndexOfMainElementHistory = 0;

            if (Detalle_de_Descripcion_de_Evidencia_CCModuleAttributeList.ChildModuleAttributeList != null)
            {
                indexOfArrayHistory          = strDetalle_de_Descripcion_de_Evidencia_CCScript.IndexOf("inpuElementChildArray");
                splittedStringHistory        = strDetalle_de_Descripcion_de_Evidencia_CCScript.Substring(indexOfArrayHistory, strDetalle_de_Descripcion_de_Evidencia_CCScript.Length - indexOfArrayHistory);
                indexOfMainElementHistory    = splittedStringHistory.IndexOf('[');
                endIndexOfMainElementHistory = splittedStringHistory.IndexOf(']') + 1;
            }
            string finalResponse = strDetalle_de_Descripcion_de_Evidencia_CCScript.Substring(0, indexOfArray + indexOfMainElement) + userChangeJson + strDetalle_de_Descripcion_de_Evidencia_CCScript.Substring(endIndexOfMainElement + indexOfArray, strDetalle_de_Descripcion_de_Evidencia_CCScript.Length - (endIndexOfMainElement + indexOfArray));

            if (Detalle_de_Descripcion_de_Evidencia_CCModuleAttributeList.ChildModuleAttributeList != null)
            {
                finalResponse = strDetalle_de_Descripcion_de_Evidencia_CCScript.Substring(0, indexOfArray + indexOfMainElement) + userChangeJson
                                + strDetalle_de_Descripcion_de_Evidencia_CCScript.Substring(endIndexOfMainElement + indexOfArray, (indexOfMainElementHistory + indexOfArrayHistory) - (endIndexOfMainElement + indexOfArray)) + childUserChangeJson
                                + strDetalle_de_Descripcion_de_Evidencia_CCScript.Substring(endIndexOfMainElementHistory + indexOfArrayHistory, strDetalle_de_Descripcion_de_Evidencia_CCScript.Length - (endIndexOfMainElementHistory + indexOfArrayHistory));
            }



            using (StreamWriter w = new StreamWriter(Server.MapPath("~/Uploads/Scripts/Detalle_de_Descripcion_de_Evidencia_CC.js")))
            {
                w.WriteLine(finalResponse);
            }

            return(Json(true, JsonRequestBehavior.AllowGet));
        }
Esempio n. 49
0
 public override IDictionary <string, object> Serialize(object obj, JavaScriptSerializer serializer)
 {
     throw new NotImplementedException();
 }
Esempio n. 50
0
        private async Task ExtractDeviceInitInfo()
        {
            try
            {
                var fileName   = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location);
                var codeLength = AppConstants.RelayCodeLength + 2;

                for (var i = 0; i < fileName.Length; i++)
                {
                    var guid = string.Join("", fileName.Skip(i).Take(36));
                    if (Guid.TryParse(guid, out _))
                    {
                        OrganizationID = guid;
                        return;
                    }


                    var codeSection = string.Join("", fileName.Skip(i).Take(codeLength));

                    if (codeSection.StartsWith("[") &&
                        codeSection.EndsWith("]") &&
                        !string.IsNullOrWhiteSpace(ServerUrl))
                    {
                        var relayCode = codeSection.Substring(1, 4);
                        using (var httpClient = new HttpClient())
                        {
                            var response = await httpClient.GetAsync($"{ServerUrl.TrimEnd('/')}/api/relay/{relayCode}").ConfigureAwait(false);

                            if (response.IsSuccessStatusCode)
                            {
                                var organizationId = await response.Content.ReadAsStringAsync();

                                OrganizationID = organizationId;
                                break;
                            }
                        }
                    }
                }

                if (!string.IsNullOrWhiteSpace(OrganizationID) &&
                    !string.IsNullOrWhiteSpace(ServerUrl))
                {
                    using (var httpClient = new HttpClient())
                    {
                        var serializer  = new JavaScriptSerializer();
                        var brandingUrl = $"{ServerUrl.TrimEnd('/')}/api/branding/{OrganizationID}";
                        using (var response = await httpClient.GetAsync(brandingUrl).ConfigureAwait(false))
                        {
                            var responseString = await response.Content.ReadAsStringAsync();

                            _brandingInfo = serializer.Deserialize <BrandingInfo>(responseString);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
            }
            finally
            {
                ApplyBranding(_brandingInfo);
            }
        }
Esempio n. 51
0
        public void ProcessRequest(HttpContext context)
        {
            int    displayLength = int.Parse(context.Request["iDisplayLength"]);
            int    displayStart  = int.Parse(context.Request["iDisplayStart"]);
            int    sortCol       = int.Parse(context.Request["iSortCol_0"]);
            string sortDir       = context.Request["sSortDir_0"];
            string search        = context.Request["sSearch"];

            string cs = ConfigurationManager.ConnectionStrings["pp"].ConnectionString;

            List <Advertisementt> listAdd = new List <Advertisementt>();
            int filteredCount             = 0;

            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("spGetAdvertisement", con);
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter paramDisplayLength = new SqlParameter()
                {
                    ParameterName = "@DisplayLength",
                    Value         = displayLength
                };
                cmd.Parameters.Add(paramDisplayLength);

                SqlParameter paramDisplayStart = new SqlParameter()
                {
                    ParameterName = "@DisplayStart",
                    Value         = displayStart
                };
                cmd.Parameters.Add(paramDisplayStart);

                SqlParameter paramSortCol = new SqlParameter()
                {
                    ParameterName = "@SortCol",
                    Value         = sortCol
                };
                cmd.Parameters.Add(paramSortCol);

                SqlParameter paramSortDir = new SqlParameter()
                {
                    ParameterName = "@SortDir",
                    Value         = sortDir
                };
                cmd.Parameters.Add(paramSortDir);

                SqlParameter paramSearchString = new SqlParameter()
                {
                    ParameterName = "@Search",
                    Value         = string.IsNullOrEmpty(search) ? null : search
                };
                cmd.Parameters.Add(paramSearchString);

                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    Advertisementt add = new Advertisementt();

                    filteredCount = Convert.ToInt32(rdr["TotalCount"]);
                    add.id        = Convert.ToInt32(rdr["advertisementId"]);
                    add.name      = rdr["advertisementName"].ToString();


                    listAdd.Add(add);
                }
            }

            var result = new
            {
                iTotalRecords        = GetPartnerTotalCount(),
                iTotalDisplayRecords = filteredCount,
                aaData = listAdd
            };

            JavaScriptSerializer js = new JavaScriptSerializer();

            context.Response.Write(js.Serialize(result));
        }
Esempio n. 52
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            //switch (result)
            //{
            //    case SignInStatus.Success:
            //        return RedirectToLocal(returnUrl);
            //    case SignInStatus.LockedOut:
            //        return View("Lockout");
            //    case SignInStatus.RequiresVerification:
            //        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            //    case SignInStatus.Failure:
            //    default:
            //        ModelState.AddModelError("", "Invalid login attempt.");
            //        return View(model);
            //}
            using (var us = new UserService.UserServiceClient())
            {
                //var result = (SignInStatus) us.ValidateUser(model);

                //var user = new ApplicationUser() { UserName = model.Username };
                //var uresult = await UserManager.CreateAsync(user, model.Password);

                var hash      = System.Security.Cryptography.SHA1.Create();
                var encoder   = new System.Text.ASCIIEncoding();
                var combined  = encoder.GetBytes(model.Password ?? "");
                var hashvalue = BitConverter.ToString(hash.ComputeHash(combined)).ToLower().Replace("-", "");

                model.Password = hashvalue;

                var result = us.ValidateUserByUsernameAndPassword(model);


                if (result != null)
                {
                    CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
                    serializeModel.Id        = result.UserID;
                    serializeModel.FirstName = result.Username;

                    JavaScriptSerializer serializer = new JavaScriptSerializer();

                    string userData = serializer.Serialize(serializeModel);

                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                        1,
                        result.Username,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(15),
                        false,
                        userData);

                    string     encTicket = FormsAuthentication.Encrypt(authTicket);
                    HttpCookie faCookie  = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                    Response.Cookies.Add(faCookie);
                    return(RedirectToLocal(returnUrl));
                }
                else
                {
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return(View(model));
                }
            }

            //var sresult = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
            //using (var us = new UserService.UserServiceClient())
            //{
            //    //var result = (SignInStatus) us.ValidateUser(model);

            //    //var user = new ApplicationUser() { UserName = model.Username };
            //    //var uresult = await UserManager.CreateAsync(user, model.Password);

            //    var hash = System.Security.Cryptography.SHA1.Create();
            //    var encoder = new System.Text.ASCIIEncoding();
            //    var combined = encoder.GetBytes(model.Password ?? "");
            //    var hashvalue = BitConverter.ToString(hash.ComputeHash(combined)).ToLower().Replace("-", "");

            //    model.Password = hashvalue;

            //    var result = us.ValidateUserByUsernameAndPassword(model);


            //    if (result != null)
            //    {
            //        FormsAuthentication.SetAuthCookie(result.UserID.ToString(), model.RememberMe);
            //        //Response.Cookies.Add(new HttpCookie("RoleId", result.RoleID.ToString()) { Expires = DateTime.Now.AddDays(-1) });
            //        //Response.Cookies.Add(new HttpCookie("UserId", result.UserID.ToString()) { Expires = DateTime.Now.AddDays(-1) });
            //        //System.Diagnostics.Debug.WriteLine("Is user authenticated? {0}", User.Identity.IsAuthenticated);
            //        //System.Diagnostics.Debug.WriteLine("Username :  {0}", User.Identity.GetUserName());
            //        return RedirectToLocal(returnUrl);
            //    }
            //    else
            //    {
            //        ModelState.AddModelError("", "Invalid login attempt.");
            //        return View(model);
            //    }
            //}
        }
Esempio n. 53
0
        public ReplayRecorder(string Server, int GameId, string Region, string Key)
        {
            //GameId = Client.GameID;
            this.GameId = GameId;
            this.Region = Region;
            this.Server = "http://" + Server;
            Directory.CreateDirectory(Path.Combine("cabinet", GameId + "-" + Region));

            File.WriteAllText(Path.Combine("cabinet", GameId + "-" + Region, "key"), Key);

            int ChunkTimeInterval;
            int LastChunk = 0;

            using (WebClient client = new WebClient())
            {
                client.DownloadFile(
                    String.Format("{0}/consumer/version", this.Server + "/observer-mode/rest"),
                    Path.Combine("cabinet", GameId + "-" + Region, "version"));

                string token = client.DownloadString(
                    String.Format("{0}/consumer/{1}/{2}/{3}/token", this.Server + "/observer-mode/rest",
                                  "getGameMetaData",
                                  Region,
                                  GameId));

                using (StreamWriter outfile = new StreamWriter(Path.Combine("cabinet", GameId + "-" + Region, "token")))
                {
                    outfile.Write(token);
                }

                JavaScriptSerializer        serializer       = new JavaScriptSerializer();
                Dictionary <string, object> deserializedJSON = serializer.Deserialize <Dictionary <string, object> >(token);

                ChunkTimeInterval = Convert.ToInt32(deserializedJSON["chunkTimeInterval"]);
                LastChunk         = Convert.ToInt32(deserializedJSON["endStartupChunkId"]);
            }

            ThreadPool.QueueUserWorkItem(delegate
            {
                if (LastChunk != 0)
                {
                    using (WebClient client = new WebClient())
                    {
                        for (int i = 1; i < LastChunk + 1; i++)
                        {
                            client.DownloadFile(
                                String.Format("{0}/consumer/{1}/{2}/{3}/{4}/token", this.Server + "/observer-mode/rest",
                                              "getGameDataChunk",
                                              Region,
                                              GameId,
                                              i),
                                Path.Combine("cabinet", GameId + "-" + Region, "chunk-" + i));

                            if (OnGotChunk != null)
                            {
                                OnGotChunk(i);
                            }

                            LastChunkNumber = i;
                        }
                    }
                }
                while (Recording)
                {
                    GetChunk();
                }
            });
        }
Esempio n. 54
0
        public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary == null)
            {
                throw new ArgumentNullException("dictionary");
            }

            return(type == typeof(object) ? new DynamicJsonObject(dictionary) : null);
        }
        /// <summary>
        /// Mailgun verification for bulk contacts
        /// </summary>
        public void MailgunVerification(List <RawContact> contacts)
        {
            var mailGunList     = new List <IEnumerable <string> >();
            var interimMailList = new List <string>();
            var mailLengthList  = contacts
                                  .Where(c => !string.IsNullOrEmpty(c.PrimaryEmail))
                                  .Select(c => new { Email = c.PrimaryEmail, Length = (c.PrimaryEmail.Length + 1) }) //adding + 1 to consider comma in final string
                                  .Distinct();

            var maxSize = 4000;
            int sum = 0; int index = 0;

            foreach (var mail in mailLengthList)
            {
                index++;
                sum = sum + mail.Length;
                if (sum >= maxSize)
                {
                    mailGunList.Add(interimMailList);
                    interimMailList = new List <string>();
                    interimMailList.Add(mail.Email);
                    sum = mail.Length;
                }
                interimMailList.Add(mail.Email);
                if (index == mailLengthList.Count())
                {
                    mailGunList.Add(interimMailList);
                }
            }

            foreach (var mailsToCheck in mailGunList)
            {
                var             emails   = string.Join(",", mailsToCheck);
                GetRestResponse response = mailGunService.BulkEmailValidate(new GetRestRequest()
                {
                    Email = emails
                });
                JavaScriptSerializer js = new JavaScriptSerializer();
                dynamic restResponse    = js.Deserialize <dynamic>(response.RestResponse.Content);

                if (restResponse != null)
                {
                    string[] valid    = ((IEnumerable)restResponse["parsed"]).Cast <object>().Select(x => x.ToString()).ToArray();
                    string[] notvalid = ((IEnumerable)restResponse["unparseable"]).Cast <object>().Select(x => x.ToString()).ToArray();

                    contacts = contacts.Join(valid, c => c.PrimaryEmail, v => v, (c, v) => c).ToList();
                    foreach (RawContact contact in contacts)
                    {
                        contact.EmailStatus = (byte)EmailStatus.Verified;
                    }

                    if (notvalid.IsAny())
                    {
                        contacts = contacts.Join(notvalid, c => c.PrimaryEmail, v => v, (c, v) => c).ToList();
                        foreach (RawContact contact in contacts)
                        {
                            contact.EmailStatus = (byte)EmailStatus.HardBounce;
                        }
                    }
                }
                else
                {
                    contacts.ForEach(p => p.EmailStatus = (byte)EmailStatus.NotVerified);
                }
            }
            importDataRepository.InsertImportContactEmailStatuses(contacts);
        }
        private void processContacts(Node node, NodeAttributes attributes,
                                     IEnumerable <FieldViewModel> customFields, int jobId,
                                     IEnumerable <DropdownValueViewModel> dropdownFields, string fileName)
        {
            #region Declarations
            StringBuilder                hash                = new StringBuilder();
            IList <Email>                emails              = new List <Email>();
            var                          guid                = Guid.NewGuid();
            RawContact                   contact             = new RawContact();
            IList <ImportCustomData>     contactCustomData   = new List <ImportCustomData>();
            IList <ImportPhoneData>      contactPhoneData    = new List <ImportPhoneData>();
            StringBuilder                customFieldData     = new StringBuilder();
            bool                         isDuplicateFromFile = false;
            LeadAdapterRecordStatus      status              = LeadAdapterRecordStatus.Undefined;
            SearchResult <Contact>       duplicateResult     = new SearchResult <Contact>();
            Dictionary <string, dynamic> oldNewValues        = new Dictionary <string, dynamic> {
            };
            #endregion

            #region BuilderNumber Validation
            string builderNumber     = attributes[_fieldMappings.GetOrDefault("BuilderNumber")].Value;
            bool   builderNumberPass = leadAdapterAndAccountMap.BuilderNumber.ToLower().Split(',').Contains(builderNumber.ToLower());
            #endregion

            #region Community Number Validation
            string communityNumber     = attributes[_fieldMappings.GetOrDefault("CommunityNumber")].Value;
            bool   communityNumberPass = true;
            #endregion

            #region ContactsProcessing
            string firstName    = attributes[_fieldMappings.GetOrDefault("FirstName")].Value;
            string lastName     = attributes[_fieldMappings.GetOrDefault("LastName")].Value;
            string primaryEmail = attributes[_fieldMappings.GetOrDefault("Email")].Value;
            string companyName  = string.Empty;

            #region HashPreparation
            Action <string> HashAppend = (n) =>
            {
                if (string.IsNullOrEmpty(n))
                {
                    hash.Append("-").Append(string.Empty);
                }
                else
                {
                    hash.Append("-").Append(n);
                }
            };

            if (!string.IsNullOrEmpty(primaryEmail))
            {
                Email _primaryemail = new Email()
                {
                    EmailId   = primaryEmail,
                    AccountID = leadAdapterAndAccountMap.AccountID,
                    IsPrimary = true
                };
                emails.Add(_primaryemail);
                hash.Append("-").Append(primaryEmail);
            }
            else
            {
                hash.Append("-").Append("*****@*****.**");
            }

            HashAppend(firstName);
            HashAppend(lastName);
            HashAppend(companyName);
            #endregion

            Person person = new Person()
            {
                FirstName   = firstName,
                LastName    = lastName,
                CompanyName = companyName,
                Emails      = emails,
                AccountID   = AccountID
            };


            if (builderNumberPass && communityNumberPass)
            {
                bool duplicatEemailCount = hashes.Any(h => !string.IsNullOrEmpty(primaryEmail) && h.Contains(primaryEmail));
                if (duplicatEemailCount ||
                    (string.IsNullOrEmpty(primaryEmail) && hashes.Where(h => h.Contains(hash.ToString())).Any()))
                {
                    isDuplicateFromFile = true;
                }
                else if (!duplicatEemailCount)
                {
                    isDuplicateFromFile = false;
                }
            }

            hashes.Add(hash.ToString());


            if (builderNumberPass && communityNumberPass)
            {
                SearchParameters parameters = new SearchParameters()
                {
                    AccountId = AccountID
                };
                IEnumerable <Contact> duplicateContacts = contactService.CheckIfDuplicate(new CheckContactDuplicateRequest()
                {
                    Person = person
                }).Contacts;
                duplicateResult = new SearchResult <Contact>()
                {
                    Results = duplicateContacts, TotalHits = duplicateContacts != null?duplicateContacts.Count() : 0
                };
            }

            if (!builderNumberPass)
            {
                status = LeadAdapterRecordStatus.BuilderNumberFailed;
            }
            else if (!communityNumberPass)
            {
                status = LeadAdapterRecordStatus.CommunityNumberFailed;
            }
            else if (isDuplicateFromFile)
            {
                status = LeadAdapterRecordStatus.DuplicateFromFile;
            }
            else if (duplicateResult.TotalHits > 0)
            {
                status = LeadAdapterRecordStatus.Updated;
                guid   = duplicateResult.Results.FirstOrDefault().ReferenceId;
            }
            else
            {
                status = LeadAdapterRecordStatus.Added;
            }


            Contact duplicatePerson = default(Person);

            if (status == LeadAdapterRecordStatus.Updated)
            {
                duplicatePerson = duplicateResult.Results.FirstOrDefault();
            }
            else
            {
                duplicatePerson = new Person();
            }

            Func <NodeAttribute, string, bool> checkIfStandardField = (name, field) =>
            {
                return(name.Name.ToLower() == _fieldMappings.GetOrDefault(field).NullSafeToLower());
            };

            try
            {
                foreach (var attribute in attributes)
                {
                    var name  = attribute.Name.ToLower();
                    var value = attribute.Value;

                    ImportCustomData customData = new ImportCustomData();
                    try
                    {
                        var elementValue = string.Empty;
                        if (checkIfStandardField(attribute, "FirstName"))
                        {
                            elementValue      = ((Person)duplicatePerson).FirstName == null ? string.Empty : ((Person)duplicatePerson).FirstName;
                            contact.FirstName = value;
                        }
                        else if (checkIfStandardField(attribute, "LastName"))
                        {
                            elementValue     = ((Person)duplicatePerson).LastName;
                            contact.LastName = value;
                        }
                        else if (checkIfStandardField(attribute, "Email"))
                        {
                            Email primaryemail = duplicatePerson.Emails.IsAny() ? duplicatePerson.Emails.Where(i => i.IsPrimary == true).FirstOrDefault() : null;
                            if (primaryemail != null)
                            {
                                elementValue = primaryemail.EmailId;
                            }
                            contact.PrimaryEmail = value;
                        }
                        else if (checkIfStandardField(attribute, "Company"))
                        {
                            // get company dynamic
                            elementValue        = duplicatePerson.CompanyName;
                            contact.CompanyName = value;
                        }
                        else if (checkIfStandardField(attribute, "PhoneNumber") || checkIfStandardField(attribute, "Phone"))
                        {
                            DropdownValueViewModel dropdownValue = dropdownFields.Where(i => i.DropdownValueTypeID == (short)DropdownValueTypes.MobilePhone).FirstOrDefault();
                            var             mobilephone          = default(Phone);
                            ImportPhoneData phoneData            = new ImportPhoneData();
                            phoneData.ReferenceID = guid;
                            if (dropdownValue != null)
                            {
                                if (!string.IsNullOrEmpty(value))
                                {
                                    string phoneNumber = GetNonNumericData(value);
                                    if (IsValidPhoneNumberLength(phoneNumber))
                                    {
                                        contact.PhoneData     = dropdownValue.DropdownValueID.ToString() + "|" + phoneNumber;
                                        phoneData.PhoneType   = (int?)dropdownValue.DropdownValueID;
                                        phoneData.PhoneNumber = phoneNumber;
                                        contactPhoneData.Add(phoneData);
                                    }
                                }
                                mobilephone = duplicatePerson.Phones.IsAny() ? duplicatePerson.Phones.Where(i => i.PhoneType == dropdownValue.DropdownValueID).FirstOrDefault() : null;
                            }

                            if (mobilephone != null)
                            {
                                elementValue = mobilephone.Number;
                            }
                        }
                        else if (checkIfStandardField(attribute, "Country"))
                        {
                            var countryvalue = value.Replace(" ", string.Empty).ToLower();
                            if (countryvalue == "usa" || countryvalue == "us" || countryvalue == "unitedstates" || countryvalue == "unitedstatesofamerica")
                            {
                                contact.Country = "US";
                            }
                            else if (countryvalue == "ca" || countryvalue == "canada")
                            {
                                contact.Country = "CA";
                            }
                            else
                            {
                                contact.Country = value;
                            }
                        }
                        else if (checkIfStandardField(attribute, "StreetAddress"))
                        {
                            contact.AddressLine1 = value;
                        }
                        else if (checkIfStandardField(attribute, "City"))
                        {
                            contact.City = value;
                        }
                        else if (checkIfStandardField(attribute, "State"))
                        {
                            contact.State = value;
                        }
                        else if (checkIfStandardField(attribute, "PostalCode"))
                        {
                            contact.ZipCode = value;
                        }
                        else
                        {
                            var customField = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == (name + "(" + leadAdapterType.ToString().ToLower() + ")")).FirstOrDefault();
                            if (customField != null)
                            {
                                var customfielddata = duplicatePerson.CustomFields == null ? null : duplicatePerson.CustomFields.Where(i => i.CustomFieldId == customField.FieldId).FirstOrDefault();
                                if (customfielddata != null)
                                {
                                    elementValue = customfielddata.Value;
                                }
                                customData.FieldID     = customField.FieldId;
                                customData.FieldTypeID = (int?)customField.FieldInputTypeId;
                                customData.ReferenceID = guid;

                                if (customField.FieldInputTypeId == FieldType.date || customField.FieldInputTypeId == FieldType.datetime || customField.FieldInputTypeId == FieldType.time)
                                {
                                    DateTime converteddate;
                                    if (DateTime.TryParse(value, out converteddate))
                                    {
                                        customFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + converteddate.ToString("MM/dd/yyyy hh:mm tt"));
                                        customData.FieldValue = converteddate.ToString("MM/dd/yyyy hh:mm tt");
                                    }
                                }
                                else if (customField.FieldInputTypeId == FieldType.number)
                                {
                                    double number;
                                    if (double.TryParse(value, out number))
                                    {
                                        customFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + number.ToString());
                                        customData.FieldValue = number.ToString();
                                    }
                                }
                                else if (customField.FieldInputTypeId == FieldType.url)
                                {
                                    if (IsValidURL(value.Trim()))
                                    {
                                        customFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + value.Trim());
                                        customData.FieldValue = value.Trim();
                                    }
                                }
                                else
                                {
                                    customFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + value.Trim());
                                    customData.FieldValue = value.Trim();
                                }
                                contactCustomData.Add(customData);
                            }
                        }
                        if (!oldNewValues.ContainsKey(attribute.Name))
                        {
                            oldNewValues.Add(attribute.Name, new { OldValue = string.IsNullOrEmpty(elementValue) ? string.Empty : elementValue, NewValue = value });
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Current.Error("An exception occured in Genereating old new values element in Trulia : " + attribute.Name, ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Current.Error("An exception occured in Genereating old new values element in Trulia : ", ex);
            }
            #endregion

            if (customFieldData.Length > 0)
            {
                customFieldData.Remove(0, 1);
            }
            contact.CustomFieldsData = customFieldData.ToString();

            contact.ReferenceId               = guid;
            contact.AccountID                 = AccountID;
            contact.IsBuilderNumberPass       = builderNumberPass;
            contact.IsCommunityNumberPass     = communityNumberPass;
            contact.LeadAdapterRecordStatusId = (byte)status;
            contact.JobID           = jobId;
            contact.ContactStatusID = 1;
            contact.ContactTypeID   = 1;
            JavaScriptSerializer js = new JavaScriptSerializer();
            contact.LeadAdapterSubmittedData = js.Serialize(oldNewValues);
            contact.LeadAdapterRowData       = node.Current != null?node.Current.ToString() : string.Empty;

            personCustomFieldData.AddRange(contactCustomData);
            personPhoneData.AddRange(contactPhoneData);

            contact.ValidEmail = ValidateEmail(contact);

            RawContact duplicate_data = null;
            if (!string.IsNullOrEmpty(contact.PrimaryEmail))
            {
                duplicate_data = persons.Where(p => string.Compare(p.PrimaryEmail, contact.PrimaryEmail, true) == 0).FirstOrDefault();
            }
            else
            {
                duplicate_data = persons.Where(p => string.Compare(p.FirstName, contact.FirstName, true) == 0 &&
                                               string.Compare(p.LastName, contact.LastName, true) == 0).FirstOrDefault();
            }

            if (duplicate_data != null)
            {
                contact.IsDuplicate = true;
                //RawContact updatedperson = MergeDuplicateData(duplicate_data, contact, guid);
                //duplicate_data = updatedperson;
            }

            persons.Add(contact);
        }
Esempio n. 57
0
        public HttpResponseMessage SalesGrowth(string year1, string year2)
        {
            List <Lib_Primavera.Model.CabecDoc> sales1 = new List <Lib_Primavera.Model.CabecDoc>();
            List <Lib_Primavera.Model.CabecDoc> sales2 = new List <Lib_Primavera.Model.CabecDoc>();
            List <SalesGrowthItem> returnList          = new List <SalesGrowthItem>();
            string key = year1 + year2;

            if (SalesController.salesGrowthCache.ContainsKey(key))
            {
                returnList = SalesController.salesGrowthCache[key];
            }
            else
            {
                sales1 = Lib_Primavera.PriIntegration.getSalesBy("year", year1, null, null);
                sales2 = Lib_Primavera.PriIntegration.getSalesBy("year", year2, null, null);

                //[i][0] totalValue1;
                //[i][1] totalValue2;
                //[i][2] percentage;
                //[i][3] dif;
                List <List <double> > quarters = new List <List <double> >();
                for (int i = 0; i < 4; i++)
                {
                    List <double> l = new List <double>();
                    for (int j = 0; j < 4; j++)
                    {
                        l.Add(0);
                    }
                    quarters.Add(l);
                }

                foreach (var entry in sales1)
                {
                    if (entry.Data.Month < 4)
                    {
                        quarters[0][0] += entry.TotalMerc + entry.TotalIva;
                    }
                    else if (entry.Data.Month < 7)
                    {
                        quarters[1][0] += entry.TotalMerc + entry.TotalIva;
                    }
                    else if (entry.Data.Month < 10)
                    {
                        quarters[2][0] += entry.TotalMerc + entry.TotalIva;
                    }
                    else if (entry.Data.Month < 13)
                    {
                        quarters[3][0] += entry.TotalMerc + entry.TotalIva;
                    }
                }

                foreach (var entry in sales2)
                {
                    if (entry.Data.Month < 4)
                    {
                        quarters[0][1] += entry.TotalMerc + entry.TotalIva;

                        //result[entry.Data.Month - 1][entry.Data.Year - year + 1] += amount;
                    }
                    else if (entry.Data.Month < 7)
                    {
                        quarters[1][1] += entry.TotalMerc + entry.TotalIva;
                    }
                    else if (entry.Data.Month < 10)
                    {
                        quarters[2][1] += entry.TotalMerc + entry.TotalIva;
                    }
                    else if (entry.Data.Month < 13)
                    {
                        quarters[3][1] += entry.TotalMerc + entry.TotalIva;
                    }
                }
                for (int i = 0; i < 4; i++)
                {
                    quarters[i][3] = quarters[i][1] - quarters[i][0];

                    if (quarters[i][0] != 0 && quarters[i][1] != 0)
                    {
                        quarters[i][2] = (quarters[i][1] - quarters[i][0]) / quarters[i][1] * 100;
                    }
                    else
                    {
                        if (quarters[i][0] == 0)
                        {
                            quarters[i][2] = quarters[i][1];
                        }
                        else if (quarters[i][1] == 0)
                        {
                            quarters[i][2] = -quarters[i][0];
                        }
                    }

                    returnList.Add(new SalesGrowthItem
                    {
                        Valor1      = quarters[i][0],
                        Valor2      = quarters[i][1],
                        Percentagem = quarters[i][2],
                        Dif         = quarters[i][3]
                    });
                }


                SalesController.salesGrowthCache.Add(key, returnList);
            }

            var json = new JavaScriptSerializer().Serialize(returnList);

            return(Request.CreateResponse(HttpStatusCode.OK, json));
        }
Esempio n. 58
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (new User().ValidateUser(txt_email.Value, txt_password.Value))
        {
            int ttid = new User().getTTId(txt_email.Value);

            if (new User().IsSectorSelected(ttid))
            {
                Session["ttid"] = ttid;
                Response.Redirect("garage.aspx");
            }
            else
            {
                Session["ttid"] = ttid;
                //Redirect user to the sector select
                Response.Redirect("selectsector.aspx");
            }
        }
        else if (!new User().ValidateUser(txt_email.Value, txt_password.Value))
        {
            JsonClass jc = new JsonClass();
            jc.Email    = txt_email.Value;
            jc.Password = txt_password.Value;
            jc.EventId  = 22;

            string    json_data = JsonConvert.SerializeObject(jc);
            WebClient c         = new WebClient();
            c.Encoding = System.Text.Encoding.UTF8;
            c.Headers[HttpRequestHeader.ContentType] = "application/json";
            try
            {
                string cs = c.UploadString("http://www.silive.in/tt15.rest/api/Student/GetStudent", json_data);
                JavaScriptSerializer json_serializer = new JavaScriptSerializer();
                Student stud = new Student();
                stud = json_serializer.Deserialize <Student>(cs);
                var i = c.ResponseHeaders;



                string query = "insert into user(ttid,username,password,email,cash,sector_id,confirmed) values(" + stud.TTId + ",'" + stud.Name + "','" + txt_password.Value + "','" + stud.Email + "',100000,0,1" + ")";

                con             = new Connect(query);
                Session["ttid"] = stud.TTId;
                Response.Redirect("selectsector.aspx");
            }
            catch (WebException ex)
            {
                HttpWebResponse response = ex.Response as HttpWebResponse;
                if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    lbl_error.Text    = "You are not registered on Techtrishna. Register Now at techtrishna 2015 website.";
                    lbl_error.Visible = true;
                }
                if (response.StatusCode == HttpStatusCode.Found)
                {
                    con = new Connect();
                    string q = "update user set password= '******' where email='" + txt_email.Value + "'";
                    con = new Connect(q);
                    int ttid = new User().getTTId(txt_email.Value);
                    if (new User().IsSectorSelected(ttid))
                    {
                        Session["ttid"] = ttid;
                        Response.Redirect("garage.aspx");
                    }
                    else
                    {
                        Session["ttid"] = ttid;
                        //Redirect user to the sector select
                        Response.Redirect("selectsector.aspx");
                    }
                }
                //lbl_error.Text = "Invalid credentials";
            }
        }
    }
Esempio n. 59
0
        /// <summary>
        /// 发送微信服务通知
        /// </summary>
        /// <param name="userOpenID">发送目的用户的openid</param>
        /// <param name="formID">提交表单的formid</param>
        /// <param name="hongBaoValueDecimal">红包值</param>
        public void SendServNotice(string userOpenID, string formID, decimal hongBaoValueDecimal, string companyID)
        {
            //通过公司id获取公司名称
            string companyName = "公司";

            if (!string.IsNullOrEmpty(companyID))
            {
                CompanysEL companyEL = new CompanysEL();
                companyEL.ID = long.Parse(companyID);
                DataTable dt_company = companyEL.ExecDT(2);
                if (dt_company != null && dt_company.Rows.Count > 0)
                {
                    companyName = dt_company.Rows[0]["CompanyName"].ToString();
                }
            }

            SortedDictionary <string, object> m_values = new SortedDictionary <string, object>();

            m_values.Add("touser", userOpenID);                                         //接收者(用户)的 openid
            m_values.Add("template_id", "2bqqDRenEIyb5D0V8ngm7BYn0tukqGdOFEYx5m2-z28"); //所需下发的模板消息的id(小程序后台配置)
            m_values.Add("page", "pages/mycard/mycard");                                //点击模板卡片后的跳转页面
            m_values.Add("form_id", formID);                                            //表单提交场景下,为 submit 事件带上的 formId;支付场景下,为本次支付的 prepay_id

            SortedDictionary <string, object> m_values_data       = new SortedDictionary <string, object>();
            SortedDictionary <string, object> m_values_data_Item1 = new SortedDictionary <string, object>();

            m_values_data_Item1.Add("value", "迎春纳福 喜送红包");//
            // m_values_data_Item1.Add("color", "#173177");//
            m_values_data.Add("keyword1", m_values_data_Item1);

            SortedDictionary <string, object> m_values_data_Item2 = new SortedDictionary <string, object>();

            m_values_data_Item2.Add("value", hongBaoValueDecimal + "元现金红包");//
            m_values_data_Item2.Add("color", "#F70909");
            m_values_data.Add("keyword2", m_values_data_Item2);

            SortedDictionary <string, object> m_values_data_Item3 = new SortedDictionary <string, object>();

            m_values_data_Item3.Add("value", "您已经成功领取" + companyName + "送出的" + hongBaoValueDecimal + "元新春红包。\n点击进入小程序,免费开启自己企业的新春红包,为好友送祝福吧!");//
            //m_values_data_Item3.Add("color", "#F70909");
            m_values_data.Add("keyword3", m_values_data_Item3);

            m_values.Add("data", m_values_data);//模板内容

            JavaScriptSerializer js = new JavaScriptSerializer();

            js.MaxJsonLength = int.MaxValue;

            string json = js.Serialize(m_values);

            BLL.Common.Logger.Error("发模板消息提交的json数据:" + json);


            //string xml = ToXml(m_values);//获取xml文件
            //BLL.Common.Logger.Error("发模板消息提交的xml数据:" + xml);

            try
            {
                //获取access_token
                WX_TokenBLL tokenBLL     = new WX_TokenBLL();
                string      access_token = tokenBLL.GetToken();
                //发送模板消息 接口地址
                string url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + access_token;
                //post提交
                //string result = apiPost(xml, url);
                string result = Post(url, json);
                BLL.Common.Logger.Error("发模板消息结果:" + result);
                //xml转换成字典
                //SortedDictionary<string, object> resultDictionary = FromXml(result);
                //BLL.Common.Logger.Error("errmsg数据:" + resultDictionary["errmsg"].ToString());
                //if (resultDictionary["errmsg"].ToString() == "ok")
                //{
                //    BLL.Common.Logger.Error("发送模板成功!");
                //}
                Dictionary <string, object> result_Dic = new Dictionary <string, object>();
                result_Dic = js.Deserialize <Dictionary <string, object> >(result);
                if (result_Dic.Keys.Contains("errcode"))
                {
                    if (result_Dic["errcode"].ToString() == "0")
                    {
                        BLL.Common.Logger.Error("发送模板成功!");
                    }
                }
            }
            catch (Exception exp)
            {
                BLL.Common.Logger.Error("发送模板错误:" + exp.ToString());
            }
        }
Esempio n. 60
0
        private string TransformToDisplayableString(object resultedObject)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            return((resultedObject is IList) ? serializer.Serialize(resultedObject) : resultedObject.ToString());
        }