bvcms /CmsData/APIFunctions.cs

Language C# Lines 370
MD5 Hash 4169ffe9bb247ee4c8e4dddc33d6db9d Estimated Cost $9,269 (why?)
Repository https://bitbucket.org/mahalowe/bvcms View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UtilityExtensions;
using System.Text.RegularExpressions;
using System.Data.Linq;
using System.Xml.Linq;
using System.Data.Linq.SqlClient;
using IronPython.Hosting;
using System.IO;
using CmsData.Codes;
using System.Web;
using System.Xml;
using System.Diagnostics;
using Microsoft.Scripting.Hosting;
using System.Xml.Serialization;

namespace CmsData.API
{
    public partial class APIFunctions
    {
        private CMSDataContext Db;

        public APIFunctions()
        {
            Db = new CMSDataContext("Data Source=.;Initial Catalog=CMS_bellevue;Integrated Security=True");
        }
        public APIFunctions(CMSDataContext Db)
        {
            this.Db = Db;
        }
        public static string TestAPI(string init, string script, Dictionary<string, string> namevalues)
        {
            var shell = @"
from System.Net import WebClient, NetworkCredential
from System.Collections.Specialized import NameValueCollection
from System.Text import Encoding
from System import Convert

{0}
class TestAPI(object):
	def Run(self):
{1}";
            try
            {
                var sb = new StringBuilder();
                var ss = (script ?? "return").Replace("\r\n", "\n");
                foreach (var s in ss.Split('\n'))
                    sb.AppendFormat("\t\t{0}\n", s);
                var engine = Python.CreateEngine();
                script = shell.Fmt(init, sb.ToString());
                var sc = engine.CreateScriptSourceFromString(script);
                var code = sc.Compile();
                var scope = engine.CreateScope();
                foreach (var i in namevalues)
                    scope.SetVariable(i.Key, i.Value);
                code.Execute(scope);
                dynamic TestAPI = scope.GetVariable("TestAPI");
                dynamic m = TestAPI();
                var ret = m.Run();
                return HttpUtility.HtmlEncode(ret);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        public string Login(Person p)
        {
            var script = Db.Content("API-LoginInfo");
            if (script == null)
            {
                script = new Content();
                script.Body = @"
from System import *
from System.Text import *

class LoginInfo(object):

	def Run(self, m, w, p):
		w.Start('Login')
		w.Attr('PeopleId', p.PeopleId)
		w.Attr('PreferredName', p.PreferredName)
		w.Attr('Last', p.LastName)
		w.Attr('EmailAddress', p.EmailAddress)
		w.Attr('IsMember', p.MemberStatusId == 10)
		for b in m.QueryBits(p.PeopleId):
			w.Add('QueryBit', b);
		w.End()
		return w.ToString()
";
            }
            var engine = Python.CreateEngine();
            var sc = engine.CreateScriptSourceFromString(script.Body);
            try
            {
                var code = sc.Compile();
                var scope = engine.CreateScope();
                code.Execute(scope);

                dynamic LoginInfo = scope.GetVariable("LoginInfo");
                dynamic m = LoginInfo();
                var api = new APIFunctions(Db);
                var w = new APIWriter();
                return m.Run(api, w, p);
            }
            catch (Exception ex)
            {
                return "<login error=\"API-LoginInfo script error: {0}\" />".Fmt(ex.Message);
            }
        }
        public int AttendCount(int orgid, int PeopleId)
        {
            var q = from a in Db.Attends
                    where a.OrganizationId == orgid
                    where a.PeopleId == PeopleId
                    where a.AttendanceFlag == true
                    select a;
            return q.Count();
        }
        public List<string> QueryBits(int PeopleId)
        {
            var q1 = (from f in Db.QueryBitsFlags()
                      select f).ToList();
            var q2 = (from t in Db.TagPeople
                      where t.PeopleId == PeopleId
                      where t.Tag.TypeId == 100
                      select t.Tag.Name).ToList();
            var q = from t in q2
                    join f in q1 on t equals f[0]
                    select f[1];
            var list = q.ToList();
            return list;
        }
        public DateTime LastAttendDate(int orgid, int PeopleId)
        {
            var q = from a in Db.Attends
                    where a.OrganizationId == orgid
                    where a.PeopleId == PeopleId
                    where a.AttendanceFlag == true
                    orderby a.MeetingDate descending
                    select a.MeetingDate;
            return q.FirstOrDefault();
        }
        public int IsMemberOf(int orgid, int PeopleId)
        {
            var q = from a in Db.OrganizationMembers
                    where a.OrganizationId == orgid
                    where a.PeopleId == PeopleId
                    where a.MemberTypeId != Codes.MemberTypeCode.InActive
                    select a;
            return q.Count();
        }
        public void DeleteExtraValue(int peopleid, string field)
        {
            var q = from v in Db.PeopleExtras
                    where v.Field == field
                    where v.PeopleId == peopleid
                    select v;
            Db.PeopleExtras.DeleteAllOnSubmit(q);
            Db.SubmitChanges();
        }
        public string ExtraValues(int peopleid, string fields)
        {
            try
            {
                var a = (fields ?? "").Split(',');
                var nofields = !fields.HasValue();
                var q = from v in Db.PeopleExtras
                        where nofields || a.Contains(v.Field)
                        where v.PeopleId == peopleid
                        select v;
                var w = new APIWriter();
                w.Start("ExtraValues");
                w.Attr("Id", peopleid);
                foreach (var v in q)
                    w.Add(v.Field, v.StrValue ?? v.Data ?? v.DateValue.FormatDate() ?? v.IntValue.ToString());
                w.End();
                return w.ToString();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        public string AddEditExtraValue(int peopleid, string field, string value, string type = "data")
        {
            try
            {
                var q = from v in Db.PeopleExtras
                        where v.Field == field
                        where v.PeopleId == peopleid
                        select v;
                var ev = q.SingleOrDefault();
                if (ev == null)
                {
                    ev = new PeopleExtra
                    {
                        PeopleId = peopleid,
                        Field = field,
                        TransactionTime = DateTime.Now
                    };
                    Db.PeopleExtras.InsertOnSubmit(ev);
                }
                else
                {
					// prepare for new data type
					ev.Data = null;
					ev.IntValue = null;
					ev.DateValue = null;
					ev.StrValue = null;
                }
                switch (type)
                {
                    case "code":
                        ev.StrValue = value;
                        break;
                    case "data":
                        ev.Data = value;
                        break;
                    case "date":
                        ev.DateValue = value.ToDate();
                        break;
                    case "int":
                        ev.IntValue = value.ToInt2();
                        break;
                }
                Db.SubmitChanges();
                return "ok";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        public string FamilyMembers(int familyid)
        {
            try
            {
                var q = from p in DbUtil.Db.People
                        where p.FamilyId == familyid
                        select p;
                var w = new APIWriter();
                w.Start("Family");
                w.Attr("Id", familyid);
                foreach (var m in q)
                {
                    w.Start("Member");
                    w.Add("peopleid", m.PeopleId);
                    w.Add("first", m.FirstName);
                    w.Add("last", m.LastName);
                    w.Add("goesby", m.NickName);
                    w.Add("birthday", m.BDate);
                    w.Add("position", m.PositionInFamilyId);
                    w.Add("marital", m.MaritalStatusId);
                    w.Add("suffix", m.SuffixCode);
                    w.Add("title", m.TitleCode);
                    w.End();
                }
                w.End();
                return w.ToString();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        [Serializable()]
        public class AccessUsers
        {
            [XmlElement("Person")]
            public AccessUserInfo[] People { get; set; }
        }
        [Serializable()]
        public class AccessUserInfo
        {
            [XmlAttribute("peopleid")]
            public int peopleid { get; set; }
            public string first { get; set; }
            public string goesby { get; set; }
            public string last { get; set; }
            public string cphone { get; set; }
            public string hphone { get; set; }
            public string wphone { get; set; }
            public string dob { get; set; }
            public int? bmon { get; set; }
            public int? bday { get; set; }
            public int? byear { get; set; }
            public int? married { get; set; }
            public int? gender { get; set; }
            public string company { get; set; }
            public string email { get; set; }
            public string email2 { get; set; }
            public string username { get; set; }
            public string lastactive { get; set; }
            public string roles { get; set; }
			public List<string> QueryBits { get; set; }
        }
        public IEnumerable<AccessUserInfo> AccessUsersData(bool includeNoAccess = false)
        {
            var q = from u in Db.Users
                    where includeNoAccess || u.UserRoles.Any(rr => rr.Role.RoleName == "Access")
                    where u.EmailAddress.Length > 0
                    select new
                    {
                        u.PeopleId,
                        roles = u.UserRoles.Select(uu => uu.Role.RoleName),
                        lastactive = Db.LastActive(u.UserId),
                        first = u.Person.FirstName,
                        goesby = u.Person.NickName,
                        last = u.Person.LastName,
                        married = u.Person.MaritalStatusId,
                        gender = u.Person.GenderId,
                        cphone = u.Person.CellPhone,
                        hphone = u.Person.HomePhone,
                        wphone = u.Person.WorkPhone,
                        dob = u.Person.DOB,
                        bday = u.Person.BirthDay,
                        bmon = u.Person.BirthMonth,
                        byear = u.Person.BirthYear,
                        company = u.Person.EmployerOther,
                        email = u.EmailAddress,
                        email2 = u.Person.EmailAddress2,
                        username = u.Username,
                    };
            var list = q.ToList();

            var q2 = from i in list
                     group i by i.PeopleId into g
                     let i1 = g.OrderByDescending(i => i.lastactive).First()
                     select new AccessUserInfo
                     {
                         peopleid = i1.PeopleId.Value,
                         first = i1.first,
                         goesby = i1.goesby,
                         last = i1.last,
                         married = i1.married,
                         gender = i1.gender,
                         cphone = i1.cphone.GetDigits(),
                         hphone = i1.hphone.GetDigits(),
                         wphone = i1.wphone,
                         dob = i1.dob,
                         bday = i1.bday,
                         bmon = i1.bmon,
                         byear = i1.byear,
                         company = i1.company,
                         email = i1.email,
                         email2 = i1.email2,
                         username = i1.username,
                         lastactive = i1.lastactive.ToString2("s"),
                         roles = string.Join(",", i1.roles),
#if DEBUG
#else
						 QueryBits = (from qb in QueryBits(i1.PeopleId.Value) select qb).ToList()
#endif
                     };
            return q2;
        }
        public string AccessUsersXml(bool includeNoAccess = false)
        {
            var xs = new XmlSerializer(typeof(AccessUsers));
            var sw = new StringWriter();
            var a = new AccessUsers { People = AccessUsersData(includeNoAccess).ToArray() };
            xs.Serialize(sw, a);
            return sw.ToString();
        }
    }
}
Back to Top