PageRenderTime 4ms CodeModel.GetById 3ms app.highlight 23ms RepoModel.GetById 1ms app.codeStats 0ms

/CmsData/APIFunctions.cs

https://bitbucket.org/rbhakser/bvcms
C# | 369 lines | 364 code | 4 blank | 1 comment | 25 complexity | 4169ffe9bb247ee4c8e4dddc33d6db9d MD5 | raw file
  1using System;
  2using System.Collections.Generic;
  3using System.Linq;
  4using System.Text;
  5using UtilityExtensions;
  6using System.Text.RegularExpressions;
  7using System.Data.Linq;
  8using System.Xml.Linq;
  9using System.Data.Linq.SqlClient;
 10using IronPython.Hosting;
 11using System.IO;
 12using CmsData.Codes;
 13using System.Web;
 14using System.Xml;
 15using System.Diagnostics;
 16using Microsoft.Scripting.Hosting;
 17using System.Xml.Serialization;
 18
 19namespace CmsData.API
 20{
 21    public partial class APIFunctions
 22    {
 23        private CMSDataContext Db;
 24
 25        public APIFunctions()
 26        {
 27            Db = new CMSDataContext("Data Source=.;Initial Catalog=CMS_bellevue;Integrated Security=True");
 28        }
 29        public APIFunctions(CMSDataContext Db)
 30        {
 31            this.Db = Db;
 32        }
 33        public static string TestAPI(string init, string script, Dictionary<string, string> namevalues)
 34        {
 35            var shell = @"
 36from System.Net import WebClient, NetworkCredential
 37from System.Collections.Specialized import NameValueCollection
 38from System.Text import Encoding
 39from System import Convert
 40
 41{0}
 42class TestAPI(object):
 43	def Run(self):
 44{1}";
 45            try
 46            {
 47                var sb = new StringBuilder();
 48                var ss = (script ?? "return").Replace("\r\n", "\n");
 49                foreach (var s in ss.Split('\n'))
 50                    sb.AppendFormat("\t\t{0}\n", s);
 51                var engine = Python.CreateEngine();
 52                script = shell.Fmt(init, sb.ToString());
 53                var sc = engine.CreateScriptSourceFromString(script);
 54                var code = sc.Compile();
 55                var scope = engine.CreateScope();
 56                foreach (var i in namevalues)
 57                    scope.SetVariable(i.Key, i.Value);
 58                code.Execute(scope);
 59                dynamic TestAPI = scope.GetVariable("TestAPI");
 60                dynamic m = TestAPI();
 61                var ret = m.Run();
 62                return HttpUtility.HtmlEncode(ret);
 63            }
 64            catch (Exception ex)
 65            {
 66                return ex.Message;
 67            }
 68        }
 69        public string Login(Person p)
 70        {
 71            var script = Db.Content("API-LoginInfo");
 72            if (script == null)
 73            {
 74                script = new Content();
 75                script.Body = @"
 76from System import *
 77from System.Text import *
 78
 79class LoginInfo(object):
 80
 81	def Run(self, m, w, p):
 82		w.Start('Login')
 83		w.Attr('PeopleId', p.PeopleId)
 84		w.Attr('PreferredName', p.PreferredName)
 85		w.Attr('Last', p.LastName)
 86		w.Attr('EmailAddress', p.EmailAddress)
 87		w.Attr('IsMember', p.MemberStatusId == 10)
 88		for b in m.QueryBits(p.PeopleId):
 89			w.Add('QueryBit', b);
 90		w.End()
 91		return w.ToString()
 92";
 93            }
 94            var engine = Python.CreateEngine();
 95            var sc = engine.CreateScriptSourceFromString(script.Body);
 96            try
 97            {
 98                var code = sc.Compile();
 99                var scope = engine.CreateScope();
100                code.Execute(scope);
101
102                dynamic LoginInfo = scope.GetVariable("LoginInfo");
103                dynamic m = LoginInfo();
104                var api = new APIFunctions(Db);
105                var w = new APIWriter();
106                return m.Run(api, w, p);
107            }
108            catch (Exception ex)
109            {
110                return "<login error=\"API-LoginInfo script error: {0}\" />".Fmt(ex.Message);
111            }
112        }
113        public int AttendCount(int orgid, int PeopleId)
114        {
115            var q = from a in Db.Attends
116                    where a.OrganizationId == orgid
117                    where a.PeopleId == PeopleId
118                    where a.AttendanceFlag == true
119                    select a;
120            return q.Count();
121        }
122        public List<string> QueryBits(int PeopleId)
123        {
124            var q1 = (from f in Db.QueryBitsFlags()
125                      select f).ToList();
126            var q2 = (from t in Db.TagPeople
127                      where t.PeopleId == PeopleId
128                      where t.Tag.TypeId == 100
129                      select t.Tag.Name).ToList();
130            var q = from t in q2
131                    join f in q1 on t equals f[0]
132                    select f[1];
133            var list = q.ToList();
134            return list;
135        }
136        public DateTime LastAttendDate(int orgid, int PeopleId)
137        {
138            var q = from a in Db.Attends
139                    where a.OrganizationId == orgid
140                    where a.PeopleId == PeopleId
141                    where a.AttendanceFlag == true
142                    orderby a.MeetingDate descending
143                    select a.MeetingDate;
144            return q.FirstOrDefault();
145        }
146        public int IsMemberOf(int orgid, int PeopleId)
147        {
148            var q = from a in Db.OrganizationMembers
149                    where a.OrganizationId == orgid
150                    where a.PeopleId == PeopleId
151                    where a.MemberTypeId != Codes.MemberTypeCode.InActive
152                    select a;
153            return q.Count();
154        }
155        public void DeleteExtraValue(int peopleid, string field)
156        {
157            var q = from v in Db.PeopleExtras
158                    where v.Field == field
159                    where v.PeopleId == peopleid
160                    select v;
161            Db.PeopleExtras.DeleteAllOnSubmit(q);
162            Db.SubmitChanges();
163        }
164        public string ExtraValues(int peopleid, string fields)
165        {
166            try
167            {
168                var a = (fields ?? "").Split(',');
169                var nofields = !fields.HasValue();
170                var q = from v in Db.PeopleExtras
171                        where nofields || a.Contains(v.Field)
172                        where v.PeopleId == peopleid
173                        select v;
174                var w = new APIWriter();
175                w.Start("ExtraValues");
176                w.Attr("Id", peopleid);
177                foreach (var v in q)
178                    w.Add(v.Field, v.StrValue ?? v.Data ?? v.DateValue.FormatDate() ?? v.IntValue.ToString());
179                w.End();
180                return w.ToString();
181            }
182            catch (Exception ex)
183            {
184                return ex.Message;
185            }
186        }
187        public string AddEditExtraValue(int peopleid, string field, string value, string type = "data")
188        {
189            try
190            {
191                var q = from v in Db.PeopleExtras
192                        where v.Field == field
193                        where v.PeopleId == peopleid
194                        select v;
195                var ev = q.SingleOrDefault();
196                if (ev == null)
197                {
198                    ev = new PeopleExtra
199                    {
200                        PeopleId = peopleid,
201                        Field = field,
202                        TransactionTime = DateTime.Now
203                    };
204                    Db.PeopleExtras.InsertOnSubmit(ev);
205                }
206                else
207                {
208					// prepare for new data type
209					ev.Data = null;
210					ev.IntValue = null;
211					ev.DateValue = null;
212					ev.StrValue = null;
213                }
214                switch (type)
215                {
216                    case "code":
217                        ev.StrValue = value;
218                        break;
219                    case "data":
220                        ev.Data = value;
221                        break;
222                    case "date":
223                        ev.DateValue = value.ToDate();
224                        break;
225                    case "int":
226                        ev.IntValue = value.ToInt2();
227                        break;
228                }
229                Db.SubmitChanges();
230                return "ok";
231            }
232            catch (Exception ex)
233            {
234                return ex.Message;
235            }
236        }
237        public string FamilyMembers(int familyid)
238        {
239            try
240            {
241                var q = from p in DbUtil.Db.People
242                        where p.FamilyId == familyid
243                        select p;
244                var w = new APIWriter();
245                w.Start("Family");
246                w.Attr("Id", familyid);
247                foreach (var m in q)
248                {
249                    w.Start("Member");
250                    w.Add("peopleid", m.PeopleId);
251                    w.Add("first", m.FirstName);
252                    w.Add("last", m.LastName);
253                    w.Add("goesby", m.NickName);
254                    w.Add("birthday", m.BDate);
255                    w.Add("position", m.PositionInFamilyId);
256                    w.Add("marital", m.MaritalStatusId);
257                    w.Add("suffix", m.SuffixCode);
258                    w.Add("title", m.TitleCode);
259                    w.End();
260                }
261                w.End();
262                return w.ToString();
263            }
264            catch (Exception ex)
265            {
266                return ex.Message;
267            }
268        }
269        [Serializable()]
270        public class AccessUsers
271        {
272            [XmlElement("Person")]
273            public AccessUserInfo[] People { get; set; }
274        }
275        [Serializable()]
276        public class AccessUserInfo
277        {
278            [XmlAttribute("peopleid")]
279            public int peopleid { get; set; }
280            public string first { get; set; }
281            public string goesby { get; set; }
282            public string last { get; set; }
283            public string cphone { get; set; }
284            public string hphone { get; set; }
285            public string wphone { get; set; }
286            public string dob { get; set; }
287            public int? bmon { get; set; }
288            public int? bday { get; set; }
289            public int? byear { get; set; }
290            public int? married { get; set; }
291            public int? gender { get; set; }
292            public string company { get; set; }
293            public string email { get; set; }
294            public string email2 { get; set; }
295            public string username { get; set; }
296            public string lastactive { get; set; }
297            public string roles { get; set; }
298			public List<string> QueryBits { get; set; }
299        }
300        public IEnumerable<AccessUserInfo> AccessUsersData(bool includeNoAccess = false)
301        {
302            var q = from u in Db.Users
303                    where includeNoAccess || u.UserRoles.Any(rr => rr.Role.RoleName == "Access")
304                    where u.EmailAddress.Length > 0
305                    select new
306                    {
307                        u.PeopleId,
308                        roles = u.UserRoles.Select(uu => uu.Role.RoleName),
309                        lastactive = Db.LastActive(u.UserId),
310                        first = u.Person.FirstName,
311                        goesby = u.Person.NickName,
312                        last = u.Person.LastName,
313                        married = u.Person.MaritalStatusId,
314                        gender = u.Person.GenderId,
315                        cphone = u.Person.CellPhone,
316                        hphone = u.Person.HomePhone,
317                        wphone = u.Person.WorkPhone,
318                        dob = u.Person.DOB,
319                        bday = u.Person.BirthDay,
320                        bmon = u.Person.BirthMonth,
321                        byear = u.Person.BirthYear,
322                        company = u.Person.EmployerOther,
323                        email = u.EmailAddress,
324                        email2 = u.Person.EmailAddress2,
325                        username = u.Username,
326                    };
327            var list = q.ToList();
328
329            var q2 = from i in list
330                     group i by i.PeopleId into g
331                     let i1 = g.OrderByDescending(i => i.lastactive).First()
332                     select new AccessUserInfo
333                     {
334                         peopleid = i1.PeopleId.Value,
335                         first = i1.first,
336                         goesby = i1.goesby,
337                         last = i1.last,
338                         married = i1.married,
339                         gender = i1.gender,
340                         cphone = i1.cphone.GetDigits(),
341                         hphone = i1.hphone.GetDigits(),
342                         wphone = i1.wphone,
343                         dob = i1.dob,
344                         bday = i1.bday,
345                         bmon = i1.bmon,
346                         byear = i1.byear,
347                         company = i1.company,
348                         email = i1.email,
349                         email2 = i1.email2,
350                         username = i1.username,
351                         lastactive = i1.lastactive.ToString2("s"),
352                         roles = string.Join(",", i1.roles),
353#if DEBUG
354#else
355						 QueryBits = (from qb in QueryBits(i1.PeopleId.Value) select qb).ToList()
356#endif
357                     };
358            return q2;
359        }
360        public string AccessUsersXml(bool includeNoAccess = false)
361        {
362            var xs = new XmlSerializer(typeof(AccessUsers));
363            var sw = new StringWriter();
364            var a = new AccessUsers { People = AccessUsersData(includeNoAccess).ToArray() };
365            xs.Serialize(sw, a);
366            return sw.ToString();
367        }
368    }
369}